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

如何将Pandas中含字典列表的列拆分为键命名的同行列并填充值

拆分字典列表列为带索引后缀的多列

如果你用Python的pandas处理这类表格数据,可以通过以下代码实现需求:

1. 准备示例数据

先构造包含目标列的数据集(匹配你提供的示例):

import pandas as pd

df = pd.DataFrame({
    'extra_column': ['demo'],
    'dict_list': [
        [
            {'genre': 'Adventure, Indie, RPG',
             'item_id': '326950',
             'discounted_price': '$8.99',
             'item_url': 'http://store.steampowered.com/app/326950',
             'item_name': 'Sword of Asumi'},
            {'genre': 'Adventure, Indie, RPG',
             'item_id': '331490',
             'discounted_price': '$2.99',
             'item_url': 'http://store.steampowered.com/app/331490',
             'item_name': 'Sword of Asumi - Soundtrack'}
        ]
    ]
})

2. 执行拆分操作

将存储字典列表的列展平为键_索引格式的新列:

# 展平字典列表并格式化列名
expanded_df = df['dict_list'].apply(pd.Series).stack().apply(pd.Series).unstack()
expanded_df.columns = [f"{col[1]}_{col[0]}" for col in expanded_df.columns]

# 合并原数据与拆分后的列,丢弃原字典列表列
final_df = pd.concat([df.drop('dict_list', axis=1), expanded_df], axis=1)

3. 最终输出

处理后的表格如下:

extra_columngenre_0item_id_0discounted_price_0item_url_0item_name_0genre_1item_id_1discounted_price_1item_url_1item_name_1
demoAdventure, Indie, RPG326950$8.99http://store.steampowered.com/app/326950Sword of AsumiAdventure, Indie, RPG331490$2.99http://store.steampowered.com/app/331490Sword of Asumi - Soundtrack

关键逻辑解释

  • apply(pd.Series):将每行的字典列表拆分为多个行,每行对应一个字典
  • stack() + unstack():重新调整索引层级,让每个字典的键成为列的一部分
  • 列名格式化:通过列表推导式将列名改为键_索引的形式,区分不同字典的同键字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:46:07