【问题标题】:Convert list of dictionaries containing another list of dictionaries with multiple values to dataframe将包含另一个具有多个值的字典列表的字典列表转换为数据框
【发布时间】:2018-05-01 15:43:11
【问题描述】:

此问题是在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

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

【问题讨论】:

    标签: python pandas dictionary dataframe


    【解决方案1】:

    我认为通过更改我对您之前问题的回答,您可以实现您想要的。还是先用空列表填充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)
    

    【讨论】:

      猜你喜欢
      • 2018-10-10
      • 2019-04-21
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2019-05-05
      • 2020-01-18
      • 2023-01-13
      • 2022-10-13
      相关资源
      最近更新 更多