如何将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_column | genre_0 | item_id_0 | discounted_price_0 | item_url_0 | item_name_0 | genre_1 | item_id_1 | discounted_price_1 | item_url_1 | item_name_1 |
|---|---|---|---|---|---|---|---|---|---|---|
| demo | Adventure, Indie, RPG | 326950 | $8.99 | http://store.steampowered.com/app/326950 | Sword of Asumi | Adventure, Indie, RPG | 331490 | $2.99 | http://store.steampowered.com/app/331490 | Sword of Asumi - Soundtrack |
关键逻辑解释
apply(pd.Series):将每行的字典列表拆分为多个行,每行对应一个字典stack()+unstack():重新调整索引层级,让每个字典的键成为列的一部分- 列名格式化:通过列表推导式将列名改为
键_索引的形式,区分不同字典的同键字段
内容的提问来源于stack exchange,提问作者Ahmed Daker
相关产品推荐
相关产品推荐

