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

如何拆分DataFrame指定列中的多值并生成多行数据?

解决方案

可以通过以下Pandas操作实现需求:

import pandas as pd

# 定义原始DataFrame
df = pd.DataFrame({'id': ['1','2','3'],
                   'fruits': ['apple, Apple','Orange, grapefruit','Melon'],
                   'count': [2,2,1]})

# 拆分多值列并展开成目标格式
result_df = df.assign(fruits=df['fruits'].str.split(', ')).explode('fruits')[['id', 'fruits']]

# 查看结果
print(result_df)

代码说明

  • df['fruits'].str.split(', '):将fruits列的字符串按, (逗号加空格)分割为列表,例如'apple, Apple'会被转为['apple', 'Apple']
  • assign(fruits=...):用分割后的列表替换原fruits列
  • explode('fruits'):将列表中的每个元素单独拆分为一行,同时保持id列的对应关系
  • [['id', 'fruits']]:筛选出最终需要的两列,剔除不需要的count列

运行后输出结果:

id      fruits
0  1       apple
0  1       Apple
1  2      Orange
1  2  grapefruit
2  3       Melon

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:45:54