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

Python与Pandas:多列作为索引时如何使用unstack或pivot?

如何对DataFrame的Property和Value列执行Unstack/Pivot操作

嘿,我来帮你搞定这个需求!首先得明确你的原始DataFrame应该是长格式的(比如包含一个唯一标识行的列,比如ID,加上Property和Value列),举个直观的例子:

原始DataFrame示例:

IDPropertyValue
1Height175
1Weight70
2Height180
2Weight80

你想要转成宽格式,把Property的取值变成列名,对应的Value填充进去对吧?下面给你几种靠谱的实现方法:

方法1:用pivot(最直观的长转宽工具)

pivot就是专门为这种场景设计的,直接指定行索引、列名来源和值的来源即可:

# 这里的'ID'是你的唯一标识列,根据实际数据替换成自己的列名
df_wide = df.pivot(index='ID', columns='Property', values='Value')

# 如果不想保留顶部的"Property"列标签,再加两步处理
df_wide = df_wide.reset_index()
df_wide.columns.name = None

执行后就能得到你期望的结构:

转换后的DataFrame:

IDHeightWeight
117570
218080

方法2:用unstack(适合已有多级索引的场景)

如果想用unstack,需要先把分组列和Property设置为多级索引,再对Property层级执行unstack操作:

# 设置多级索引,只保留Value列,再展开Property层级
df_wide = df.set_index(['ID', 'Property'])['Value'].unstack('Property')

# 同样可以重置索引并去掉列名标签
df_wide = df_wide.reset_index()
df_wide.columns.name = None

这个方法和pivot效果完全一致,适合已经有索引结构的数据集。

处理重复值的特殊情况

如果你的原始数据里,同一个ID+Property组合有多行记录,pivot会直接报错。这时候可以用pivot_table,指定聚合函数来合并重复值,比如取第一个值、平均值或者求和:

# 这里用aggfunc='first'取第一个出现的值,你可以换成'mean'/'sum'等聚合方式
df_wide = df.pivot_table(
    index='ID',
    columns='Property',
    values='Value',
    aggfunc='first'
).reset_index()
df_wide.columns.name = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:12:03