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

将含多值嵌套字典列表的字典列表转换为DataFrame(API参数新增后)

解决嵌套字典列表转DataFrame的问题

嘿,我来帮你搞定这个API返回的复杂结构转DataFrame的需求!这种带嵌套列表的字典结构用pandas的json_normalize就能轻松处理,下面是具体步骤和示例:

核心思路

你的数据里actions字段是嵌套的字典列表,我们需要把这部分展开成单独的行,同时保留顶层的account_id、cust_id等关联字段,json_normalize正好是干这个的神器。

具体代码实现

1. 先把Insights对象转成字典列表(如果API返回的是对象而非字典)

如果你的insights是类实例列表,先转换成普通字典列表:

# 假设Insights对象的属性可以通过__dict__获取
data = [insight.__dict__ for insight in insights]
# 如果对象有to_dict()方法,也可以用这个:data = [insight.to_dict() for insight in insights]

2. 用json_normalize展开嵌套结构

直接调用pandas的json_normalize函数,指定要展开的嵌套字段和要保留的顶层字段:

import pandas as pd

df = pd.json_normalize(
    data,  # 你的字典列表数据
    record_path='actions',  # 要展开的嵌套列表字段名
    meta=['account_id', 'cust_id', 'cust_name'],  # 需要保留的顶层字段
    errors='ignore'  # 忽略缺失字段,避免报错
)

示例效果

假设你的输入数据是:

insights = [
    {
        "account_id": "1234",
        "actions": [{'value': '5', 'action_type': 'add_to_cart', 'view': '5'}],
        "cust_id": "xyz123",
        "cust_name": "xyz"
    },
    {
        "account_id": "1234",
        "actions": [
            {'value': '3', 'action_type': 'purchase', 'view': '2'},
            {'value': '1', 'action_type': 'view', 'view': '1'}
        ],
        "cust_id": "abc456",
        "cust_name": "abc"
    }
]

运行代码后得到的DataFrame会是这样的:

valueaction_typeviewaccount_idcust_idcust_name
5add_to_cart51234xyz123xyz
3purchase21234abc456abc
1view11234abc456abc

额外注意点

  • 如果actions字段可能为空列表,json_normalize会自动生成空行(或者根据需求调整参数)
  • 如果顶层字段有缺失,errors='ignore'会自动填充NaN,避免程序崩溃
  • 要是你的API返回的是JSON字符串,记得先用json.loads()转成字典列表再处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:06:30