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

如何按不同RecordType列拆分DataFrame并重组列结构?

按RecordType拆分DataFrame并生成独立列的高效方法

原始数据结构

RecordType    SSID    AchievementLevel  ScaleScore
1             4234    1                  32
1             4321    4                  43
2             3432    2                  23
2             8878    2                  43
6             9809    3                  65
6             7807    2                  34

需求说明

按RecordType拆分DataFrame,让每个类型对应独立的AchievementLevel和ScaleScore列,替代拆分后左连接的低效实现方式。


高效实现方法

方法1:pivot(无重复SSID+RecordType组合时首选)

直接通过pivot重塑数据,将RecordType整合到列名中:

# 执行pivot操作,SSID作为索引,RecordType作为列维度,指定要拆分的指标列
df_pivoted = df.pivot(index='SSID', columns='RecordType', values=['AchievementLevel', 'ScaleScore'])

# 重命名列名,让结构更直观(比如AchievementLevel_RT1)
df_pivoted.columns = [f'{metric}_RT{rt}' for metric, rt in df_pivoted.columns]

# 重置索引,将SSID从索引变回普通列
df_pivoted = df_pivoted.reset_index()

输出结果中,每个RecordType会对应一组AchievementLevel_RT{x}和ScaleScore_RT{x}列,无匹配的SSID会填充NaN。

方法2:stack/unstack组合

通过索引的堆叠与展开实现重塑,适合需要灵活操作索引的场景:

# 将SSID和RecordType设为多层索引,再按RecordType展开列
df_stacked = df.set_index(['SSID', 'RecordType']).unstack('RecordType')

# 重命名列名
df_stacked.columns = [f'{metric}_RT{rt}' for metric, rt in df_stacked.columns]

# 重置索引
df_stacked = df_stacked.reset_index()

逻辑与pivot一致,但能更灵活地处理多层索引的中间操作。

方法3:pivot_table(存在重复SSID+RecordType组合时)

如果同一SSID+RecordType存在重复行,用pivot_table指定聚合规则处理:

df_pivot_table = df.pivot_table(
    index='SSID',
    columns='RecordType',
    values=['AchievementLevel', 'ScaleScore'],
    aggfunc='first'  # 根据需求替换为'mean'/'sum'等聚合函数
)

# 重命名列并重置索引
df_pivot_table.columns = [f'{metric}_RT{rt}' for metric, rt in df_pivot_table.columns]
df_pivot_table = df_pivot_table.reset_index()

优势说明

以上方法均基于Pandas内置的向量化重塑逻辑,比手动拆分后逐个左连接高效得多——尤其是数据量较大时,能显著减少内存占用和运行时间,避免循环或多次连接带来的性能损耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:17:02