Python中如何将DataFrame从行级结构转换为列级结构
Pandas DataFrame 长格式转宽格式解决方案
核心思路
通过Pandas的pivot或pivot_table方法,将以Type为分组的行数据转换为列,实现长表到宽表的转换。
代码实现
- 构造示例数据(模拟你的原始DataFrame)
import pandas as pd df = pd.DataFrame({ 'name': ['AAA', 'AAA', 'AAA'], 'Type': [1, 2, 3], 'value': ['Increase', 'Decrease', 'Neutral'] })
- 执行长转宽操作
# 使用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()
- 查看结果
运行后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
相关产品推荐
相关产品推荐

