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

Pandas中将含逗号分隔列表的多列合并为新列c4的需求

Pandas 多列按分隔符拆分后合并生成新列的实现方法

原始DataFrame定义

import pandas as pd

df = pd.DataFrame({
                 'c1':['a','f,g,e','a,f,e,h','g,h','b,c,g,h',],
                 'c2':['1','1,1,0.5','1,2,2.5,1','3,1','2,-1,0.5,-1'],
                 'c3':['0.05','0.01,0.001,>0.5','>0.9,>0.9,0.01,0.002','>0.9,>0.9','0.05,0.1,<0.01,0.1'],
             })

原始输出

c1            c2                          c3
0        a             1                        0.05
1    f,g,e       1,1,0.5          0.01,0.001,>0.5
2  a,f,e,h   1,2,2.5,1  >0.9,>0.9,0.01,0.002
3      g,h           3,1                >0.9,>0.9
4  b,c,g,h  2,-1,0.5,-1        0.05,0.1,<0.01,0.1

需求说明

需要将c1、c2、c3三列按逗号拆分后,按位置一一对应合并生成新列c4,每个元素格式为元素(c2对应值|c3对应值),多个元素用逗号分隔,预期结果如下:

c1            c2                          c3                                            c4
0        a             1                        0.05                                      a(1|0.05)
1    f,g,e       1,1,0.5          0.01,0.001,>0.5               f(1|0.01),g(1|0.001),e(0.5|>0.5)
2  a,f,e,h   1,2,2.5,1  >0.9,>0.9,0.01,0.002  a(1|>0.9),f(2|>0.9),e(2.5|0.01),h(1|0.002)
3      g,h           3,1                >0.9,>0.9                            g(3|>0.9),h(1|>0.9)
4  b,c,g,h  2,-1,0.5,-1        0.05,0.1,<0.01,0.1       b(2|0.05),c(-1|0.1),g(0.5|<0.01),h(-1|0.1)

注:预期结果中h(1|0.02)应为h(1|0.002),g(0.5<0.01)应为g(0.5|<0.01),属于输入笔误,以下实现按正确格式生成

实现代码

def generate_c4(row):
    # 拆分各列字符串为列表
    c1_items = row['c1'].split(',')
    c2_items = row['c2'].split(',')
    c3_items = row['c3'].split(',')
    # 按位置配对并格式化每个元素
    combined_parts = [f"{item1}({item2}|{item3})" for item1, item2, item3 in zip(c1_items, c2_items, c3_items)]
    # 拼接成最终字符串
    return ','.join(combined_parts)

# 应用函数生成c4列
df['c4'] = df.apply(generate_c4, axis=1)

# 查看结果
print(df.to_string())

代码说明

  • 定义generate_c4函数逐行处理数据:
    1. 将c1、c2、c3列的字符串按逗号拆分为列表;
    2. 使用zip将三个列表的对应元素一一配对;
    3. 按照指定格式拼接每一组配对元素;
    4. 将所有拼接好的元素用逗号连接成最终字符串。
  • 通过df.apply将函数应用到每一行,生成c4列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:07:02