Python pandas 如何调整 DataFrame 列的顺序?
调整列顺序最直接的方式是按新顺序重新选择列:df = df[['col3', 'col1', 'col2']];把某列提前用 insert+pop 组合。本文给出重排、前置、排序三种写法。
最通用:用新顺序的列名列表重新索引——df = df[['c', 'a', 'b']],DataFrame 即按该顺序排列。
整体重排
df = df[['name', 'age', 'city']] # 按指定顺序
# 想要"某几列在前,其余保持原顺序"
cols = ['id', 'name'] + [c for c in df.columns if c not in ['id', 'name']]
df = df[cols]
单列提前/移后
# 把 'score' 列移到最前
col = df.pop('score')
df.insert(0, 'score', col)
# 移到指定位置(第 3 位)
df.insert(2, 'score', df.pop('score'))
按字母排序
df = df[sorted(df.columns)]
# 或
df = df.sort_index(axis=1)
常见问题(FAQ)
Q:df.reindex(columns=[...]) 和直接选择有区别吗? 直接选择更直观;reindex 允许列不存在(补 NaN),注意别引入空列。
Q:能原地改吗? pop/insert 是原地操作;df[cols] 是生成新视图赋回 df,效果相同。