python - 将包含另一个具有多个值的字典列表的字典列表转换为数据帧

标签 python pandas dictionary dataframe

此问题是对Convert list of dictionaries containing another list of dictionaries to dataframe 上发布的问题的补充。

我被要求在 API 调用中添加一个参数,现在输出变得比上面的有点复杂。

输出是这样的:

insights = [ <Insights> "account_id": "1234",
                    "actions": [{'value': '5', 'action_type': 'add_to_cart', 'view': '5'}],
                    "cust_id": "xyz123",
                    "cust_name": "xyz",
}, <Insights> {
    "account_id": "1234",
    "cust_id": "pqr123",
    "cust_name": "pqr",
},  <Insights> {
    "account_id": "1234",
    "actions": [
        {'click': '8', 'value': '110', 'action_type': 'add_to_cart', 'view': '102'}, {'value': '12', 'action_type': 'purchase', 'view': '12'}
    ],
    "cust_id": "abc123",
    "cust_name": "abc",
 }
 ]

现在我想要这样的解决方案

- account_id a2cart_view a2cart_click pur_view pur_click cust_id cust_name
- 1234                 5                                   xyz123 xyz
- 1234                                                     pqr123 pqr
- 1234               102           8        12             abc123 abc

我尝试使用上述链接中的解决方案,但当程序无法在其中一行中找到特定值时陷入困境。

最佳答案

我认为通过改变我对你之前问题的回答,你可以实现你想要的。仍然从用空列表填充 nan 开始:

df['actions'][df['actions'].isnull()] = df['actions'][df['actions'].isnull()].apply(lambda x: [])

然后使用另一个参数what定义函数find_action:

def find_action (list_action, action_type, what):
    for action in list_action:
        # for each action, see if the key action_type is the one wanted and what in the keys
        if action['action_type'] == action_type and what in action.keys():
            return action[what]
    # if not the right action type found, then empty
    return ''

现在,您可以使用带有两个参数的 apply :

df['a2cart_view'] = df['actions'].apply(find_action, args=(['add_to_cart','view']))
df['a2cart_click'] = df['actions'].apply(find_action, args=(['add_to_cart','click']))
df['pur_view'] = df['actions'].apply(find_action, args=(['purchase','view']))
df['pur_click'] = df['actions'].apply(find_action, args=(['purchase','click']))

然后删除列actions:

df = df.drop('actions',axis=1)

关于python - 将包含另一个具有多个值的字典列表的字典列表转换为数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119490/

相关文章:

python - Pandas 直方图 : plot histogram for each column as subplot of a big figure

python 从字典创建 pandas DF。 columns_name = 字典的值,如果该值在字典值中,则 df 中的值 = 1,否则为 0

.net - (Linq)字典 : Except not returning a Dictionary

python - 堆叠水平条形图,图例位于图内。我怎样才能让这个情节更明显

python - 如何使我的 python 脚本独立且具有 webdriver 依赖项?

python - 如何在Python条形图中添加x轴刻度标签

python - 带有可选字典键值的字符串格式

python - 如何在 python 中实现一个可以从故障中恢复的方式持久保存到磁盘的字典?

python - 使用 Python GData API,无法获取可编辑的视频条目

python - 强化学习如何通过高斯策略进行连续控制?