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

Python中如何将DataFrame从行级结构转换为列级结构

Pandas DataFrame 长格式转宽格式解决方案

核心思路

通过Pandas的pivot或pivot_table方法,将以Type为分组的行数据转换为列,实现长表到宽表的转换。

代码实现

  1. 构造示例数据(模拟你的原始DataFrame)
import pandas as pd

df = pd.DataFrame({
    'name': ['AAA', 'AAA', 'AAA'],
    'Type': [1, 2, 3],
    'value': ['Increase', 'Decrease', 'Neutral']
})
  1. 执行长转宽操作
# 使用pivot转换,指定索引、列、值字段
wide_df = df.pivot(index='name', columns='Type', values='value')

# 重命名列名,将数字Type改为Type1/Type2/Type3格式
wide_df.columns = [f'Type{col}' for col in wide_df.columns]

# 重置索引,让name从索引变回普通列(可选,按需调整)
wide_df = wide_df.reset_index()
  1. 查看结果
    运行后wide_df的结构即为你需要的格式:
name     Type1     Type2    Type3
0  AAA  Increase  Decrease  Neutral

特殊情况处理

如果你的原始数据中存在重复的(name, Type)组合(即同一name对应同一Type有多个value),建议使用pivot_table并指定聚合函数,避免报错:

wide_df = df.pivot_table(
    index='name',
    columns='Type',
    values='value',
    aggfunc='first'  # 取第一个出现的值,也可根据需求用sum/mean等
)
wide_df.columns = [f'Type{col}' for col in wide_df.columns]
wide_df = wide_df.reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:32:35