pandas DataFrame保留指定列位置并对剩余列按列名字母排序的实现方法
实现方案
你可以通过拆分列名列表、拼接排序后剩余列的方式实现需求,不需要手动罗列所有列名,仅需2行代码即可完成:
# 构造新的列顺序:前2列保持原位置,剩余列按列名字母升序排列 new_col_order = df.columns[:2].to_list() + sorted(df.columns[2:]) # 对DataFrame的列重排 df = df[new_col_order]
效果验证
重排后调用df.head()即可得到你期望的输出:
subject timepoint a b c d 0 1 1 2 2 2 2 1 1 2 3 3 3 3 2 1 3 4 4 4 4 3 1 4 5 5 5 5 4 1 5 6 6 6 6
拓展说明
如果你的需求是固定保留指定列名(而非固定前两列位置),可以调整列拆分规则,比如:
fixed_cols = ['subject', 'timepoint'] new_col_order = fixed_cols + sorted(col for col in df.columns if col not in fixed_cols) df = df[new_col_order]
这样即使前两列位置发生变化,也能保证指定列始终排在最前面,剩余列按字母顺序排列。
内容的提问来源于stack exchange,提问作者Dr Wampa
相关产品推荐
相关产品推荐

