j d*_*doe 10 python dataframe pandas
我有一个包含 100 多列的 pandas 数据框。例如在以下 df 中:
df['A','B','C','D','E','date','G','H','F','I']
Run Code Online (Sandbox Code Playgroud)
如何将日期移动到最后一列?假设数据帧很大并且我无法手动编写所有列名称。
Qua*_*ang 19
你可以试试这个:
new_cols = [col for col in df.columns if col != 'date'] + ['date']
df = df[new_cols]
Run Code Online (Sandbox Code Playgroud)
测试数据:
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
Run Code Online (Sandbox Code Playgroud)
代码的输出:
A B C D E G H F I date
0 0 1 2 3 4 6 7 8 9 5
Run Code Online (Sandbox Code Playgroud)
使用pandas.DataFrame.pop和pandas.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)
Run Code Online (Sandbox Code Playgroud)
输出:
col2 col3 col1
0 11 111 1
1 22 222 2
2 33 333 3
Run Code Online (Sandbox Code Playgroud)