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

将含嵌套字典列表的字典列表转换为DataFrame求助

解决Python API返回的嵌套Insights数据转DataFrame问题

看来你需要把带嵌套actions数组的Insights列表转换成扁平的Pandas DataFrame对吧?这里有两种常见的处理方式,完全适配不同的业务需求场景:

方式1:将每个Action展开为单独行

这种方式会把每个action条目拆成独立一行,同时保留对应的客户、账户信息,适合需要查看每一条行为明细的场景。

代码实现

import pandas as pd

# 先把API返回的Insights对象转为字典(如果是自定义类,可使用`dict(insight_obj)`或`insight_obj.__dict__`)
insights = [
    {"account_id": "1234", 
     "actions": [{"action_type": "add_to_cart", "value": "8"}, {"action_type": "purchase", "value": "2"}], 
     "cust_id": "xyz123", 
     "cust_name": "xyz"},
    {"account_id": "1234", 
     "cust_id": "pqr123", 
     "cust_name": "pqr"},
    {"account_id": "1234", 
     "actions": [{"action_type": "purchase", "value": "45"}], 
     "cust_id": "abc123", 
     "cust_name": "abc"}
]

# 为没有actions的条目补上空列表,避免后续处理报错
for item in insights:
    item.setdefault("actions", [])

# 使用json_normalize一键展开嵌套结构
df = pd.json_normalize(
    insights,
    record_path="actions",  # 指定要展开的嵌套列表字段
    meta=["account_id", "cust_id", "cust_name"],  # 指定要保留的顶层字段
    errors="ignore"
)

# 可选:把value转为数值类型,方便后续统计计算
df["value"] = pd.to_numeric(df["value"], errors="coerce")

print(df)

输出结果

action_type  value account_id cust_id cust_name
0  add_to_cart    8.0       1234  xyz123       xyz
1     purchase    2.0       1234  xyz123       xyz
2          NaN    NaN       1234  pqr123       pqr
3     purchase   45.0       1234  abc123       abc

方式2:将Action类型转为列(按客户汇总)

如果需要按客户维度汇总不同行为的数据,可以把action_type转为列,每个客户仅占一行:

代码实现

# 基于方式1生成的df进行透视转换
pivot_df = df.pivot_table(
    index=["account_id", "cust_id", "cust_name"],
    columns="action_type",
    values="value",
    aggfunc="sum",  # 同一个客户有多个同类型行为时,用sum汇总
    fill_value=0
).reset_index()

# 去掉列索引的名称,让表格更整洁
pivot_df.columns.name = None

print(pivot_df)

输出结果

account_id cust_id cust_name  add_to_cart  purchase
0       1234  abc123       abc          0.0      45.0
1       1234  pqr123       pqr          0.0       0.0
2       1234  xyz123       xyz          8.0       2.0

小提示

  • 如果API返回的是自定义Insights类实例,记得先把每个实例转为字典(比如dict(insight)或者访问insight.__dict__,具体取决于类的实现)。
  • 如果value字段存在非数值内容,pd.to_numeric会自动将其转为NaN,你可以根据需求调整errors参数。

内容的提问来源于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 09:52:05