将包含另一个具有多个值的词典列表的词典列表转换为数据框 [英] Convert list of dictionaries containing another list of dictionaries with multiple values to dataframe

查看:47
本文介绍了将包含另一个具有多个值的词典列表的词典列表转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是在我被要求在我的API调用中添加一个参数,现在输出已变得比上面的复杂一些.

I was asked to add a Parameter in my API call and now the output has become a bit complicated than the above one.

输出是这样的:

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",
 }
 ]

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

Now I want the solution something like this

- 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

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

I tried using the solution at the above link, but getting stuck when the program cannot find a particular value in one of the rows.

推荐答案

我认为,通过更改对上一个问题的回答,您可以实现所需的目标.仍然要先用空白列表填充nan:

I think by changing my answer to your previous question, you can achieve what you want. Still start by filling nan with empty list:

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

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

Then define the function find_action with another parameter what:

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与两个参数一起使用:

Now, you can use apply with two arguments:

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)

这篇关于将包含另一个具有多个值的词典列表的词典列表转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆