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

如何使用Pandas按值类型拆分单列生成新列实现长表转宽表

问题原因

你的循环代码报错是因为无Volume数据的分组中,不存在Value type = Volume的行,直接用loc['Volume']取值会触发KeyError。

最优实现方案

用pandas原生的pivot_table方法实现,向量化操作效率远高于手动遍历groupby,代码如下:

import pandas as pd

# 1. 透视表转换结构
df_new = df.pivot_table(
    index=["Year", "Product"],
    columns="Value type",
    values="Value",
    aggfunc="first"
).reset_index().rename_axis(columns=None)

# 2. 填充Volume列缺失值为你需要的占位符,可替换为任意值如'无数据'、'-'等
df_new["Volume"] = df_new["Volume"].fillna("占位符")
原有循环代码的修复方案

如果要保留原有的遍历逻辑,把取值逻辑改为用字典get方法规避KeyError即可:

container = []
for label, _df in df.groupby(['Year','Product']):
    # 转成字典后用get方法取值,不存在的key返回默认占位符
    type_value_map = _df.set_index("Value type")["Value"].to_dict()
    container.append(pd.DataFrame({
        "Product": [label[1]],
        "Price": [type_value_map.get("Price")],
        "Volume": [type_value_map.get("Volume", "占位符")],
        "Year": [label[0]]
    }))
df_new = pd.concat(container, ignore_index=True)
unstack方法的正确实现

你之前用unstack失败大概率是索引设置错误,正确写法如下:

df_new = df.set_index(["Year", "Product", "Value type"])["Value"].unstack(fill_value="占位符").reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:57:02