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

合并DataFrame中含嵌套列表的列,按对应索引生成新列

合并DataFrame列表列生成嵌套格式新列

给定如下DataFrame,需将list1、list2、list3三列合并,生成格式符合要求的list4列:

import pandas as pd

df = pd.DataFrame()

list1 = [['Smith', 'Johnson', 'David'], ['Perry', 'Windler']]
list2 = [['C', 'SF', 'PG'], ['SF', 'SG']]
list3 = [['Injured', 'Injured', 'Not Injured'], ['Not Injured', 'Injured']]

df['list1'] = list1
df['list2'] = list2
df['list3'] = list3

实现代码

通过apply逐行处理,将每行对应位置的元素拼接后嵌套为单元素列表:

def merge_rows(row):
    return [[f"{name} - {pos} - {status}"] for name, pos, status in zip(row['list1'], row['list2'], row['list3'])]

df['list4'] = df.apply(merge_rows, axis=1)

验证结果

执行后df['list4']的输出为:

0    [[Smith - C - Injured], [Johnson - SF - Injured], [David - PG - Not Injured]]
1    [[Perry - SF - Not Injured], [Windler - SG - Injured]]
Name: list4, dtype: object

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:22:04