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'))
pop 会立即移除列;若后续 insert 因位置、重名等原因失败,原 DataFrame 已被改变,应先验证参数或保留副本。
按字母排序
df = df[sorted(df.columns)]
# 或
df = df.sort_index(axis=1)
常见问题(FAQ)
Q:df.reindex(columns=[...]) 和直接选择有区别吗? 直接选择更直观;reindex 允许列不存在(补 NaN),注意别引入空列。
Q:能原地改吗? pop/insert 是原地操作;df[cols] 返回新的 DataFrame 再绑定给 df,不能概括为固定的视图或等同于原地修改;其他引用的行为不同。