首页 > 解决方案 > 将熊猫数据框中的列移动到大型数据框中的最后一列的最佳方法

问题描述

我有一个超过 100 列的熊猫数据框。例如在下面的df中:

df['A','B','C','D','E','date','G','H','F','I']

如何将日期移动到最后一列?假设数据框很大,我无法手动编写所有列名。

标签: pythonpandasdataframe

解决方案


You can try this:

new_cols = [col for col in df.columns if col != 'date'] + ['date']
df = df[new_cols]

Test data:

cols = ['A','B','C','D','E','date','G','H','F','I']
df = pd.DataFrame([np.arange(len(cols))],
                  columns=cols)

print(df)
#    A  B  C  D  E  date  G  H  F  I
# 0  0  1  2  3  4     5  6  7  8  9

Output of the code:

   A  B  C  D  E  G  H  F  I  date
0  0  1  2  3  4  6  7  8  9     5

推荐阅读