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

如何使用pandas将宽格式DataFrame转换为指定长格式结果

pandas宽格式转指定长格式的实现方案

你可以通过melt融表、分组聚合、unstack转置三步操作完成需求,完整可运行代码如下:

import pandas as pd

# 构造原始数据
data = {'colour':["red", "blue", "yellow", "red", "yellow"],
        'apple':[1, 2, 4, 5, 6], 
        'organge': [3, 4, 5, 7, 8],
        'watermelon': [7, 8, 9, 1, 0]}
df = pd.DataFrame(data)

# 核心转换逻辑
# 1. 将水果列从宽表转为长表
long_df = df.melt(id_vars="colour", var_name="fruit", value_name="num")
# 2. 按水果、颜色分组求和后转置颜色为列
result = long_df.groupby(["fruit", "colour"])["num"].sum().unstack().reset_index()
# 可选:调整列顺序为你示例的 fruit、red、blue、yellow
result = result[["fruit", "red", "blue", "yellow"]]

print(result)

运行后输出结果完全匹配你的预期:

fruit  red  blue  yellow
0       apple    6     2      10
1     organge   10     4      13
2  watermelon    8     8       9

操作逻辑说明

  • melt操作:保留colour列为固定标识,把原本分散在不同列的水果名转为fruit列,对应数值存入num列,完成宽表转基础长表
  • 分组聚合:按水果类型、颜色两个维度汇总数值
  • unstack操作:把行维度的颜色值转为列维度的表头,再重置索引得到最终格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:24:05