You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按成本类别+年份升序对Pandas DataFrame列名排序?

Pandas DataFrame列按成本类别分组、年份升序排序

完整实现代码

import pandas as pd

# 示例数据
df = pd.DataFrame({'2019 Material cost': [25, 12, 15, 14, 19, 23, 25, 29],
                   '2019 Overhead cost ': [5, 7, 7, 9, 12, 9, 9, 4],
                   '2019 Labor cost': [11, 8, 10, 6, 6, 5, 9, 12],
                   '2020 Material cost': [25, 12, 15, 14, 19, 23, 25, 29],
                   '2020 Overhead cost ': [5, 7, 7, 9, 12, 9, 9, 4],
                   '2020 Labor cost': [11, 8, 10, 6, 6, 5, 9, 12],
                   '2021 Material cost': [25, 12, 15, 14, 19, 23, 25, 29],
                   '2021 Overhead cost ': [5, 7, 7, 9, 12, 9, 9, 4],
                   '2021 Labor cost': [11, 8, 10, 6, 6, 5, 9, 12],
                  })

# 拆分列名并清理格式
split_cols = df.columns.str.split(n=1, expand=True)
split_cols.columns = ['year', 'cost_type']
split_cols['cost_type'] = split_cols['cost_type'].str.strip()

# 按成本类别、年份排序后获取列索引
sorted_col_indices = split_cols.sort_values(by=['cost_type', 'year']).index

# 重排DataFrame列
df_sorted = df.iloc[:, sorted_col_indices]

# 验证结果
print(df_sorted.columns.tolist())

步骤说明

  1. 拆分列名:用str.split(n=1, expand=True)将每个列名按第一个空格拆分为「年份」和「成本类别」两部分,避免成本类别内部空格干扰拆分。
  2. 清理格式:通过str.strip()去除成本类别末尾的多余空格(比如示例中"Overhead cost "的尾部空格),保证类别匹配一致。
  3. 排序索引:以「成本类别」为第一排序键、「年份」为第二排序键对拆分后的DataFrame排序,提取排序后的原列索引。
  4. 重排列顺序:用iloc根据排序后的索引重新排列原DataFrame的列,得到目标结构。

简化写法

如果追求代码简洁,也可以用一行完成排序:

df_sorted = df.reindex(
    sorted(df.columns, key=lambda x: (x.split(n=1)[1].strip(), x.split(n=1)[0]))
)

这里的lambda函数直接指定排序规则:先按清理后的成本类别排序,再按年份升序排序,最后通过reindex重排列。

内容的提问来源于stack exchange,提问作者Marc Irmler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:30:33