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

如何在Pandas DataFrame中分组并按条件拼接列值

问题:按分组拼接指定条件的列值并生成新列

原始DataFrame:

id1          id2          id3   lan term      
0 100000000006 100000023268 10000 en  Abnormal pain
1 100000000006 100000023268 10000 zh  jhkghdgh 
2 100000000006 100000023268 10000 cs  ghjdgfhgd 
3 100000000006 100000023268 10000 nl  jgfhgjhgfh
4 100000000006 100000023268 10000 fr  hgdhfghjgeh
5 100000000006 100000023269 10000 en  pain
6 100000000006 100000023269 10000 fr  hgdhfghjgehd
7 100000000006 100000023269 10000 nl  hgdhfghjgehdff

需求:按id1、id2、id3分组,将lan不为'en'的term值用|拼接成新列synonyms,同时保留每组lan='en'对应的term值。

现有未过滤的代码:

join_unique = lambda x: '|'.join(x.unique())
df_meddra_qtt = df_meddra.groupby(['id1', 'id2', 'id3'], as_index=False).agg(join_unique)

解决方案

方法一:拆分处理后合并

先提取每组的英文term,再单独处理非英文term的拼接,最后合并结果:

# 提取每组lan为en的term
df_en = df_meddra[df_meddra['lan'] == 'en'].copy()

# 过滤非en的行,分组拼接term得到synonyms(去除term前后空格)
df_synonyms = df_meddra[df_meddra['lan'] != 'en'].groupby(['id1', 'id2', 'id3'], as_index=False)['term'].agg(
    lambda x: '|'.join(x.str.strip())
)
df_synonyms.rename(columns={'term': 'synonyms'}, inplace=True)

# 合并两个DataFrame
df_result = df_en.merge(df_synonyms, on=['id1', 'id2', 'id3'], how='left')

方法二:聚合时指定列的处理逻辑

直接在分组聚合阶段,对不同列设置针对性处理规则,一步得到结果:

def get_en_term(series):
    # 取当前组中lan为en的term(假设每组仅一个en条目)
    return series[df_meddra.loc[series.index, 'lan'] == 'en'].iloc[0]

def join_non_en_terms(series):
    # 过滤当前组中lan不为en的term,去除空格后拼接
    non_en_terms = series[df_meddra.loc[series.index, 'lan'] != 'en'].str.strip()
    return '|'.join(non_en_terms)

df_result = df_meddra.groupby(['id1', 'id2', 'id3'], as_index=False).agg(
    term=('term', get_en_term),
    synonyms=('term', join_non_en_terms)
)

说明

  • 两种方法均可实现需求,方法一逻辑直观易调试,方法二代码更紧凑。
  • str.strip()用于清理term值前后的空格(示例中zh的term存在尾空格),若无需清理可直接移除。
  • 默认每组仅存在一个lan='en'的条目,若有多条可根据需求调整get_en_term逻辑(如取第一条、拼接所有en term等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:22:53