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

如何将Pandas中transform('unique')输出转为逗号分隔字符串而非列表

问题:如何将Pandas分组后的列表列转为逗号分隔字符串?

嘿,我来帮你搞定这个问题!你遇到的核心问题是:用groupby+transform('unique')生成的Multi Name列里的元素其实是numpy数组,不是字符串类型——而str.strip('[]')这类字符串方法只能处理字符串元素,对非字符串的数组直接用就会返回NaN,这就是为什么你之前的操作失效了。

下面给你两种实用的解决办法:

方法1:对现有数组列用apply转换

直接用apply遍历每个数组元素,把数组里的字符串用逗号连接起来:

import pandas as pd

# 你的原始DataFrame
df = pd.DataFrame({'ID':[1,1,2,2,3,4],'Name':['John Doe','Jane Doe','John Smith','Jane Smith','Jack Hill','Jill Hill']})

# 分组提取唯一值得到数组列
df['Multi Name'] = df.groupby('ID')['Name'].transform('unique')

# 将数组转为逗号分隔的字符串
df['Multi Name'] = df['Multi Name'].apply(lambda x: ', '.join(x))

执行后你会得到预期的格式化结果:

IDNameMulti Name
1John DoeJohn Doe, Jane Doe
1Jane DoeJohn Doe, Jane Doe
2John SmithJohn Smith, Jane Smith
2Jane SmithJohn Smith, Jane Smith
3Jack HillJack Hill
4Jill HillJill Hill

方法2:分组时直接生成字符串(一步到位)

你也可以跳过生成数组列的步骤,在分组transform的时候直接处理成字符串,这样更高效:

df['Multi Name'] = df.groupby('ID')['Name'].transform(lambda x: ', '.join(x.unique()))

这个方法和上面的结果完全一致,而且避免了后续对数组的转换操作。

小提示:如果你的Name列里存在缺失值,记得先处理掉,不然join会报错——可以在unique()后面加dropna(),比如写成x.unique().dropna()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:08