如何在Pandas中将指定列移至开头且保留其余列顺序?
Pandas DataFrame指定列移至开头的快速实现
问题场景
有列数不确定(10-20列)的Pandas DataFrame,列名示例包括RecordID、price、company、date等。需要将指定的若干列(仅保留DataFrame中存在的)移至DataFrame开头,其余列严格保持原有顺序不变。比如指定date、volume、price、return时,因volume不存在,最终列顺序应为date, price, return, RecordID, company, feature1, some_inf, feature2, feature3, ...
示例数据
import pandas as pd column_names = ["RecordID", "price", "company", "date", "feature1", "return", "some_inf", "feature2", "feature3"] values = [1, 9.99, "ABC", 20230101, 888, 0.666, "happy_everyday", "helloworld", "test"] df = pd.DataFrame(values).T df.columns = column_names
快速实现代码
用列表推导式筛选列后重新索引DataFrame即可,逻辑简单高效:
# 指定要移到开头的列集合 target_cols = ["date", "volume", "price", "return"] # 筛选出目标列中存在于DataFrame的列(保留指定顺序) existing_targets = [col for col in target_cols if col in df.columns] # 提取原列中不在目标列里的部分(严格保持原顺序) remaining_cols = [col for col in df.columns if col not in existing_targets] # 重新排列列顺序 df = df[existing_targets + remaining_cols] # 验证结果 print(df.columns.tolist()) # 输出:['date', 'price', 'return', 'RecordID', 'company', 'feature1', 'some_inf', 'feature2', 'feature3']
逻辑说明
- 先过滤目标列,只保留DataFrame中存在的列,避免触发
KeyError; - 遍历原列名提取非目标列,确保这部分完全遵循原有顺序;
- 将两部分列名拼接后重新索引DataFrame,完成列顺序调整。
内容的提问来源于stack exchange,提问作者XYZ
相关产品推荐
相关产品推荐

