Pandas分组拼接字符串:去重与消除前置逗号需求
Pandas分组拼接字符串的优化方案
原始场景与问题
首先定义初始DataFrame及拼接代码:
import pandas as pd df = pd.DataFrame({ 'id': [1, 1, 2, 2, 3, 3], 'txt': ['sth', 'sth else', 'sth', 'one more thing', 'sth else', 'sth else'], 'status': ['open', 'open', 'closed', 'open', 'open', 'open']}) # 初始拼接实现 initial_df = df.assign(output= df.where(df.status=='open') .groupby(df.id) .txt.transform(lambda col: ', '.join(col.fillna(''))) )
执行后得到的初始结果存在两个问题:
id txt status output 0 1 sth open sth, sth else 1 1 sth else open sth, sth else 2 2 sth closed , one more thing 3 2 one more thing open , one more thing 4 3 sth else open sth else, sth else 5 3 sth else open sth else, sth else
需要解决的两个优化点:
- 去除拼接后txt的重复值(如第4、5行的重复内容)
- 消除因
status='closed'导致的前置逗号(如第2、3行)
优化实现
方案1:分组后处理再合并
def process_group(group): # 过滤当前分组内status为open的行,提取txt列 open_txt = group[group['status'] == 'open']['txt'] # 去重后拼接成字符串 return ', '.join(open_txt.unique()) # 计算每个id对应的output值,再合并回原DataFrame id_output_map = df.groupby('id').apply(process_group).reset_index(name='output') final_df = df.merge(id_output_map, on='id', how='left')
方案2:使用transform简化写法
final_df = df.assign(output= df.groupby('id').transform( lambda g: ', '.join(g[g['status']=='open']['txt'].unique()) )['txt'] )
最终结果
执行优化代码后得到目标结果:
id txt status output 0 1 sth open sth, sth else 1 1 sth else open sth, sth else 2 2 sth closed one more thing 3 2 one more thing open one more thing 4 3 sth else open sth else 5 3 sth else open sth else
优化说明
- 去重处理:通过
unique()方法提取分组内status='open'的txt唯一值,避免重复内容拼接 - 消除前置逗号:先过滤
status='open'的行再处理,不再依赖fillna('')填充空值,从根源避免了空字符串导致的前置逗号
内容的提问来源于stack exchange,提问作者corianne1234
相关产品推荐
相关产品推荐

