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

Pandas DataFrame多值列合并方法技术咨询

解决方案

可以通过以下步骤实现需求:

  1. 拆分Column 2和Column 3的字符串为列表,将每一行的分类与对应数值配对成字典
  2. 将字典转换为DataFrame,与原数据的Column 1合并
  3. 调整列的顺序,确保a、b、c按指定顺序排列

完整代码示例

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Column 1': ['hello', 'hi'],
    'Column 2': ['a,b,c', 'b,c,a'],
    'Column 3': ['1,2,3', '4,5,6']
})

# 拆分字符串并配对成字典,转换为DataFrame
split_df = df.apply(
    lambda row: pd.Series(
        dict(zip(row['Column 2'].split(','), row['Column 3'].split(',')))
    ),
    axis=1
).astype(int)

# 合并原始Column1和转换后的DataFrame,调整列顺序
result = pd.concat([df['Column 1'], split_df], axis=1)[['Column 1', 'a', 'b', 'c']]

print(result)

输出结果

Column 1abc
hello123
hi645

代码说明

  • df.apply(..., axis=1):按行处理数据,将每一行的Column 2和Column 3拆分后,用zip配对成键值对,再转为Series
  • astype(int):将字符串类型的数值转为整数类型
  • pd.concat:将原始的Column 1和转换后的分类列合并,最后通过列名列表调整列的显示顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:05:56