繁体   English   中英

将 pandas dataframe 中的列移动到大型 dataframe 中的最后一列的最佳方法

[英]Best way to move a column in pandas dataframe to last column in large dataframe

我有一个超过 100 列的 pandas dataframe。 例如在下面的df中:

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

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

你可以试试这个:

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

测试数据:

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的代码:

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

使用pandas.DataFrame.poppandas.concat

print(df)
   col1  col2  col3
0     1    11   111
1     2    22   222
2     3    33   333

s = df.pop('col1')
new_df = pd.concat([df, s], 1)
print(new_df)

Output:

   col2  col3  col1
0    11   111     1
1    22   222     2
2    33   333     3

这边走:

df_new=df.loc[:,df.columns!='date']
df_new['date']=df['date']

简单的重新索引应该可以完成这项工作:

original = df.columns
new_cols = original.delete(original.get_loc('date'))
df.reindex(columns=new_cols)

您可以使用reindexunion

df.reindex(df.columns[df.columns != 'date'].union(['date']), axis=1) 

让我们只使用索引标题而不是完整的 dataframe。

然后,使用 reindex 对列重新排序。

Output 使用@QuangHoang 设置:

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

您可以在 Python 中使用 movecolumn package 来移动列:

pip install movecolumn

然后您可以将代码编写为:

import movecolumn as mc
mc.MoveToLast(df,'date')

希望有帮助。

PS:package 可以在这里找到。 https://pypi.org/project/movecolumn/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM