【发布时间】:2020-02-13 08:54:45
【问题描述】:
我正在对 Facebook 进行 API 调用,其中一个字段是“操作”,它创建了一个字典,我想将其分解为单独的 DataFrame 列。我已经看到一些类似的问题,使用 pd.Series() 将它们映射到单独的列或 json.normalize() 中,但这些问题并不完全符合我的要求。
这是我将其放入数据框列之前的导出:
[<AdsInsights> {
"actions": [
{
"action_type": "landing_page_view",
"value": "292"
},
{
"action_type": "comment",
"value": "13"
},
{
"action_type": "onsite_conversion.post_save",
"value": "6"
},
{
"action_type": "link_click",
"value": "874"
},
{
"action_type": "post",
"value": "1"
},
{
"action_type": "post_reaction",
"value": "393"
},
{
"action_type": "post_engagement",
"value": "96"
},
{
"action_type": "page_engagement",
"value": "96"
},
{
"action_type": "omni_activate_app",
"value": "5"
},
{
"action_type": "omni_app_install",
"value": "2"
},
{
"action_type": "omni_add_to_cart",
"value": "75"
},
{
"action_type": "add_to_wishlist",
"value": "14"
},
{
"action_type": "omni_purchase",
"value": "4"
},
{
"action_type": "omni_search",
"value": "12"
},
{
"action_type": "omni_view_content",
"value": "15"
}
]
然后我将其放入 DF 中,但该列变成了操作,它将所有这些数据放入一行,然后为每个项目重复它。我无法将 action_type 分解为列标题并将值分解为行。创建 DF 时,我得到了多行这些数据集。
当我制作数据框时,它看起来像这样:
df[ad] df[actions]
0 ad1 [{'action_type': 'landing_page_view', 'value':...
1 ad2 [{'action_type': 'landing_page_view', 'value':...
2 ad3 [{'action_type': 'landing_page_view', 'value':...
我希望得到:
df[ad] df[landing_page_view] df[comment] ...etc
0 ad1 292 13
1 ad2 100 8
2 ad3 80 9
我试图挑选出我想要制作专栏的具体内容,但这不起作用:
df = all of the raw data from the API call
df = pd.DataFrame(df)
actions = df['actions']
def setcolumn(dict, key):
if dict.has_key(key):
df['key'] = 'value'
else:
print ("Not present")
setcolumn(actions, 'landing_page_view')
但这表示系列对象没有属性has_key。
感谢任何方向!
【问题讨论】:
标签: python pandas facebook dictionary series