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

使用Pandas Pivot Table处理多值列分组及格式规范问题

Pandas 数据集格式转换:多值列拆分与同组合并

问题背景

需将含多值年级字段的数据集转换为ID1+ID2唯一组合对应单行的结构:

  • 拆分favorite_grades中以空格分隔的多值为独立年级条目
  • 同一ID1+ID2组合下,同年级姓名合并为带双引号的字符串列表

原始数据:

ID1    ID2        name    favorite_grades
 01      01        John     3rd 4th
 01      01        Kate     4th 5th
 01      02        Emily    4th
 01      03        Mark     5th
 01      03        Emma     5th 

期望输出:

ID1     ID2      3rd_grade         4th_grade      5th_grade  
 01      01         "John"          "John, Kate"   "Kate"
 01      02                         "Emily"
 01      03                                      "Mark, Emma"

现有代码问题:

  • ID1仅首行显示
  • favorite_grades中的多值未拆分,被当作独立列

解决步骤

1. 拆分多值列并展开行

先将favorite_grades按空格拆分为列表,再将每个年级条目展开为单独行:

# 拆分年级列并展开
df['grade'] = df['favorite_grades'].str.split(' ')
df_exploded = df.explode('grade').drop(columns='favorite_grades')

2. 透视表合并并格式化结果

通过透视表按ID1+ID2分组,合并同年级姓名,再添加双引号并调整列名:

# 生成透视表,合并同组姓名
pivot_df = df_exploded.pivot_table(
    index=['ID1', 'ID2'],
    columns='grade',
    values='name',
    aggfunc=', '.join,
    fill_value=''
).reset_index()

# 重命名列名,添加_grade后缀
pivot_df.columns = [f'{col}_grade' if col not in ['ID1', 'ID2'] else col for col in pivot_df.columns]

# 为姓名字符串添加双引号
for col in pivot_df.columns:
    if '_grade' in col:
        pivot_df[col] = pivot_df[col].apply(lambda x: f'"{x}"' if x else '')

效果说明

  • 执行后ID1会在每行正常显示,解决了仅首行展示的问题
  • 多值年级已被正确拆分,同ID1+ID2组合下的同年级姓名合并为带双引号的格式
  • 空值区域显示为空字符串,与期望结果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:18:19