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

如何透视含多对应值列的分类列,实现企业单行列展示?

实现表格透视(Pivot)操作

原始数据表格

CompanyCategoryYear1Year2Year3
MCOnline102025
MCOn-site141820
BKOnline503433
BKOn-site303131

目标透视后表格

CompanyYear1-OnlineYear1-On-siteYear2-OnlineYear2-On-siteYear3-OnlineYear3-On-site
MC101420182520
BK503034313331

实现代码(Python Pandas)

import pandas as pd

# 构造原始数据
data = {
    'Company': ['MC', 'MC', 'BK', 'BK'],
    'Category': ['Online', 'On-site', 'Online', 'On-site'],
    'Year1': [10, 14, 50, 30],
    'Year2': [20, 18, 34, 31],
    'Year3': [25, 20, 33, 31]
}
df = pd.DataFrame(data)

# 1. 将年份列转换为行数据,保留Company和Category作为标识列
melted_df = df.melt(id_vars=['Company', 'Category'], var_name='Year', value_name='Value')

# 2. 透视表格,将Year和Category组合为新列名
pivoted_df = melted_df.pivot(index='Company', columns=['Year', 'Category'], values='Value')
pivoted_df.columns = [f'{year}-{category}' for year, category in pivoted_df.columns]

# 3. 重置索引,让Company成为普通列
pivoted_df = pivoted_df.reset_index()

# 输出结果
print(pivoted_df)

代码说明

  • melt操作:把原表格中的Year1/Year2/Year3列转为行,生成Year和Value列,让每个年份-分类的组合对应一条数据。
  • pivot操作:以Company为行索引,将Year和Category的组合作为列,填充对应Value。
  • 列名拼接:把多级列名合并为年份-分类的格式,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:09:23