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

Pandas如何将含嵌套列表的字典转换为拆分多列的DataFrame

实现方法

你只需要在初始构造DataFrame后,对存储嵌套列表的列做逐行展开即可,完整实现代码如下:

import pandas as pd

data = {'a': 'test', 'b': 1657, 'c': 'asset', 'd': [['2089', '0.0'], ['2088', '0.0']], 'e': [['2088', '0.0'], ['2088', '0.0'], ['2088', '0.00']]}
df = pd.DataFrame({ key:pd.Series(value) for key, value in data.items() })

# 配置需要拆分的原列名和拆分后的目标列名
split_config = {'d': ['d1', 'd2'], 'e': ['e1', 'e2']}

for col, target_names in split_config.items():
    # 逐行将列表转为Series,自动按行索引对齐,缺失值自动填充NaN
    expanded = df[col].apply(lambda x: pd.Series(x) if isinstance(x, list) else pd.Series([None]*len(target_names)))
    expanded.columns = target_names
    df = pd.concat([df, expanded], axis=1)

# 移除拆分前的原始嵌套列
df = df.drop(columns=split_config.keys())

运行上述代码后得到的输出完全匹配预期:

a       b      c    d1   d2    e1    e2
0  test  1657.0  asset  2089  0.0  2088   0.0
1   NaN     NaN    NaN  2088  0.0  2088   0.0
2   NaN     NaN    NaN   NaN  NaN  2088  0.00

说明:如果后续有其他需要拆分的嵌套列表列,只需要在split_config中添加对应配置即可,不需要修改其他逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 18:33:25