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

Python Pandas宽表转长表时如何保留多列拆分后值的对应关系

解决方案

核心逻辑是对两个待拆分列同步处理后批量展开,保证拆分后的取值按原始位置一一对应,以下是可直接运行的代码:

方法1:Pandas 1.3.0及以上版本(推荐)

直接使用explode的多列同时展开能力:

import pandas as pd

# 构造示例数据,你可以替换成自己的DataFrame读取逻辑
df = pd.DataFrame({
    'ID': [123, 567],
    'History': ['555 - Pancreatic cancer,444 - Hypertension', '77 - Stroke'],
    'Relationship': ['1 - Mother,2 - Father', '2 - Father']
})

# 对两列按逗号拆分生成列表
df['History'] = df['History'].str.split(',')
df['Relationship'] = df['Relationship'].str.split(',')

# 同时展开两列,自动按位置匹配
df = df.explode(['History', 'Relationship'], ignore_index=True)

运行后输出的df就是你需要的结果。

方法2:低版本Pandas兼容方案

如果你的Pandas版本低于1.3.0,不支持多列explode,可以用打包元组的方式实现:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'ID': [123, 567],
    'History': ['555 - Pancreatic cancer,444 - Hypertension', '77 - Stroke'],
    'Relationship': ['1 - Mother,2 - Father', '2 - Father']
})

# 将每行两列拆分后的结果打包成元组列表
df['tmp'] = df.apply(
    lambda row: list(zip(row['History'].split(','), row['Relationship'].split(','))),
    axis=1
)

# 展开元组列表
df = df.explode('tmp', ignore_index=True)

# 拆分临时元组列到对应字段,删除临时列
df[['History', 'Relationship']] = pd.DataFrame(df['tmp'].tolist(), index=df.index)
df = df.drop('tmp', axis=1)

注意事项

需保证每行的History和Relationship列按逗号拆分后的元素数量完全一致,否则会出现值错位或者报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:24:02