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

如何将DataFrame中字典列表列拆分为多行?

解决方案

你可以通过Pandas的explode()和json_normalize()方法组合实现需求,步骤如下:

  1. 拆分字典列表:使用explode()将items列中的每个字典单独拆分为一行,同时保留其他列的对应值
  2. 解析字典为列:用json_normalize()将拆分后的字典列展开为item_id和item_name两列
  3. 合并结果:将原DataFrame的非items列与展开后的字典列合并,得到最终结果

完整代码示例

import pandas as pd

# 模拟你的原始DataFrame
data = {
    'order_id': ['1001', '1002'],
    'customer': ['Alice', 'Bob'],
    'items': [
        [{'item_id': 'A001', 'item_name': 'Apple'}, {'item_id': 'A002', 'item_name': 'Banana'}],
        [{'item_id': 'B001', 'item_name': 'Orange'}]
    ]
}
df = pd.DataFrame(data)

# 步骤1:拆分items列的字典列表
df_exploded = df.explode('items', ignore_index=True)

# 步骤2:将字典解析为单独的列
items_df = pd.json_normalize(df_exploded['items'])

# 步骤3:合并得到最终DataFrame
final_df = pd.concat([df_exploded.drop('items', axis=1), items_df], axis=1)

print(final_df)

运行后输出的结果就是你期望的格式:

order_id customer item_id item_name
0     1001    Alice    A001      Apple
1     1001    Alice    A002     Banana
2     1002      Bob    B001     Orange

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:05:46