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

如何从字典列表生成多列?Facebook广告数据解析需求

拆分Facebook广告数据中的actions和action_value字典列表列

直接用Pandas的apply+pivot组合就能把这两个字典列表列拆成独立字段,步骤如下:

1. 处理actions列

先把每行的actions列表转为小DataFrame,再将action_type作为列名、value作为对应值,转成宽格式后合并回原表:

import pandas as pd

# 假设你的原始数据存储在df中
# 拆分actions列
actions_expanded = df['actions'].apply(pd.DataFrame).reset_index()
actions_wide = actions_expanded.pivot(
    index='index',
    columns='action_type',
    values='value'
).add_prefix('action_')  # 给列名加前缀避免冲突

# 合并并删除原列
df = df.merge(actions_wide, left_index=True, right_index=True).drop('actions', axis=1)

2. 处理action_value列

用完全相同的逻辑处理action_value列,只是前缀换成action_value_:

# 拆分action_value列
action_value_expanded = df['action_value'].apply(pd.DataFrame).reset_index()
action_value_wide = action_value_expanded.pivot(
    index='index',
    columns='action_type',
    values='value'
).add_prefix('action_value_')

# 合并并删除原列
df = df.merge(action_value_wide, left_index=True, right_index=True).drop('action_value', axis=1)

3. 可选:处理缺失值

如果某些行没有特定action类型的数据,拆分后会出现NaN,可统一填充为0(根据数据类型调整):

# 填充数值型缺失值为0
df = df.fillna(0)

示例效果

假设原始数据某行是:

date: 2024-01-01, campaign_name: 夏季促销, actions: [{"action_type":"link_click","value":"20"}, {"action_type":"post_engagement","value":"8"}], action_value: [{"action_type":"link_click","value":"160"}, {"action_type":"post_engagement","value":"40"}]

拆分后该行会变为:

date: 2024-01-01, campaign_name: 夏季促销, action_link_click: 20, action_post_engagement: 8, action_value_link_click: 160, action_value_post_engagement: 40

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:39:32