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

如何将Pandas DataFrame中的嵌套列表列转换为多列列表列

解决方法

先构造示例数据:

import pandas as pd

df = pd.DataFrame({
    'col1': [[[1,2],[1,2]], [[3,4],[3,4]], [[5,6],[5,6]]]
})

方法一:使用apply快速转换

直接通过apply遍历每行数据,提取嵌套列表的对应元素生成新列表:

# 生成新列
df[['col1', 'col2']] = df['col1'].apply(
    lambda x: pd.Series([
        [sub_list[0] for sub_list in x],  # 提取每个子列表的第一个元素组成新列表
        [sub_list[1] for sub_list in x]   # 提取每个子列表的第二个元素组成新列表
    ])
)

# 查看结果
print(df)

输出结果:

col1       col2
0  [1, 1]  [2, 2]
1  [3, 3]  [4, 4]
2  [5, 5]  [6, 6]

方法二:使用explode+groupby处理(适合复杂场景)

如果嵌套结构更复杂,可先展开再聚合:

# 展开嵌套列表为多行
temp_df = df.explode('col1').reset_index()
# 将子列表拆分为两列
temp_df[['a', 'b']] = pd.DataFrame(temp_df['col1'].tolist(), index=temp_df.index)
# 按原索引分组,将元素重新组合为列表
result_df = temp_df.groupby('index').agg(
    col1=('a', list),
    col2=('b', list)
).reset_index(drop=True)

# 查看结果
print(result_df)

内容的提问来源于stack exchange,提问作者Rajan Kumar Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:50:19