将数据框架中的字典列表扁平化



我正在使用Facebook Insights API获取数据,并且我得到的数据中有嵌套的列。我尝试按索引分隔它们,但失败了。

要分割的列:

[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}]

我要翻译的状态:

actions_video_view  actions_link_click
1                   1
xx = dataframe['actions'].apply(pd.Series).merge(dataframe["index"],
right_index=True,
left_index=True).melt(id_vars=['index'],
value_name='actions')
xx2 = xx['action_type'].apply(pd.Series).merge(xx["index"],
right_index=True, 
left_index=True)
xx2 = xx2.loc[xx2['action_type'] == 'video_view', ["value", "index"]]

当我运行这段代码时,我得到以下错误:

Traceback (most recent call last):
File "C:ProgramDataAnaconda3libsite-packagespandascoreframe.py", line 3458, in __getitem__
indexer = self.columns.get_loc(key)
File "C:ProgramDataAnaconda3libsite-packagespandascoreindexesbase.py", line 3363, in get_loc      
raise KeyError(key) from err
KeyError: 'action_type'

我想根据键分离列并将其添加为数据框列,我可以使用哪种方式?

在数据中显示的示例:

actions
[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}]
[{'action_type': 'link_click', 'value': '3'}, {'action_type': 'video_view', 'value': '3'}]
[{'action_type': 'link_click', 'value': '5'}, {'action_type': 'video_view', 'value': '5'}]
[{'action_type': 'link_click', 'value': '6'}, {'action_type': 'video_view', 'value': '6'}]
[{'action_type': 'link_click', 'value': '7'}, {'action_type': 'video_view', 'value': '7'}]

如果我想应用:

actions_link_click  actions_video_view
1                    1
3                    3
5                    5
6                    6
7                    7

我认为您应该看看数据框的每一行是如何生成的。我认为这不是直截了当的。但对于你目前的问题,这里有一个解决方案:

import pandas as pd
import json
def convert_df(col):
tmp = col.apply(pd.Series)
out = (tmp.assign(idx=tmp.groupby('action_type').cumcount())
.pivot(index='idx', columns='action_type', values='value')
.add_prefix('actions_').rename_axis(columns=None).reset_index(drop=True))
return out
rows = [[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}],
[{'action_type': 'link_click', 'value': '3'}, {'action_type': 'video_view', 'value': '3'}],
[{'action_type': 'link_click', 'value': '5'}, {'action_type': 'video_view', 'value': '5'}],
[{'action_type': 'link_click', 'value': '6'}, {'action_type': 'video_view', 'value': '6'}],
[{'action_type': 'link_click', 'value': '7'}, {'action_type': 'video_view', 'value': '7'}],]

df = pd.DataFrame({'actions' : rows})
df = pd.json_normalize(df['actions'])
df = pd.concat([
convert_df(df[0]),
convert_df(df[1])
], axis=1)
print(df)
actions_link_click actions_video_view
0                  1                  1
1                  3                  3
2                  5                  5
3                  6                  6
4                  7                  7

最新更新