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

如何转换DataFrame格式,将长表转为按月份分组的指定宽表结构

Pandas 长表转指定宽表实现方法

依赖库

仅需要pandas库即可完成转换。

完整实现代码

首先构造和示例结构一致的DataFrame(你已有数据可跳过这一步):

import pandas as pd

df = pd.DataFrame({
    'Month': ['Jan','Jan','Jan','Feb','Feb','Feb'],
    'ID': [1,2,3,1,2,3],
    'a': [0.1, 0.02, 0.1, 0.2, 0.3, 0.1],
    'b': [0.3, 0.5, 0.4, 0.5, 0.1, 0.2],
    'c': [0.5, 0.1, 0.7, 0.5, 0.3, 0.05]
})

方法1:set_index + unstack 组合实现

# 将Month和ID设为多级行索引,再把ID维度转到列索引
res = df.set_index(['Month', 'ID']).unstack('ID')
# 拼接两级列名,格式为「指标名_ID」
res.columns = [f'{col[0]}_{col[1]}' for col in res.columns]
# 重置索引,把Month从索引转为普通列
res = res.reset_index()

方法2:直接使用pivot方法(更简洁)

# 直接指定行、列、值维度做透视
res = df.pivot(index='Month', columns='ID', values=['a','b','c']).reset_index()
# 处理列名,去掉空后缀
res.columns = [f'{x}_{y}' if y else x for x,y in res.columns]

特殊场景兼容(存在重复的Month+ID组合)

如果数据中存在同一个月同一个ID有多条记录的情况,可以用pivot_table指定聚合规则:

# 示例聚合规则为取均值,可根据需求替换为sum、max等
res = df.pivot_table(index='Month', columns='ID', values=['a','b','c'], aggfunc='mean').reset_index()
res.columns = [f'{x}_{y}' if y else x for x,y in res.columns]

执行后得到的res即为所需的宽表格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:09:02