繁体   English   中英

将包含另一个词典列表的词典列表转换为数据框

[英]Convert list of dictionaries containing another list of dictionaries to dataframe

我试图寻找解决方案,但无法获得1。我从python中的api获得以下输出。

insights = [ <Insights> {
    "account_id": "1234",
    "actions": [
        {
            "action_type": "add_to_cart",
            "value": "8"
        },
        {
            "action_type": "purchase",
            "value": "2"
        }
    ],
    "cust_id": "xyz123",
    "cust_name": "xyz",
}, <Insights> {
    "account_id": "1234",
    "cust_id": "pqr123",
    "cust_name": "pqr",
},  <Insights> {
    "account_id": "1234",
    "actions": [
        {
            "action_type": "purchase",
            "value": "45"
        }
    ],
    "cust_id": "abc123",
    "cust_name": "abc",
 }
 ]

我想要这样的数据框

- account_id    add_to_cart purchase    cust_id cust_name
- 1234                    8        2    xyz123  xyz
- 1234                                  pqr123  pqr
- 1234                            45    abc123  abc

当我使用以下

> insights_1 = [x for x in insights]

> df = pd.DataFrame(insights_1)

我得到以下

- account_id                                       actions  cust_id cust_name
- 1234  [{'value': '8', 'action_type': 'add_to_cart'},{'value': '2', 'action_type': 'purchase'}]                                    xyz123  xyz
- 1234                                              NaN     pqr123  pqr
- 1234  [{'value': '45', 'action_type': 'purchase'}]        abc123  abc

我该如何前进?

这是一种解决方案。

df = pd.DataFrame(insights)

parts = [pd.DataFrame({d['action_type']: d['value'] for d in x}, index=[0])
         if x == x else pd.DataFrame({'add_to_cart': [np.nan], 'purchase': [np.nan]})
         for x in df['actions']]

df = df.drop('actions', 1)\
       .join(pd.concat(parts, axis=0, ignore_index=True))

print(df)

  account_id cust_id cust_name add_to_cart purchase
0       1234  xyz123       xyz           8        2
1       1234  pqr123       pqr         NaN      NaN
2       1234  abc123       abc         NaN       45

说明

  • 利用pandas将字典的外部列表读入数据框。
  • 对于内部词典,请使用列表理解和字典理解。
  • 通过测试列表理解中的相等性来计算nan值。
  • 连接零件并将其连接到原始数据框。

说明-详细

这详细说明了parts的构造和使用:

  1. df['actions']每个条目; 每个条目将是词典列表
  2. for循环中逐个(即逐行)迭代它们。
  3. else部分说,“如果是np.nan [即空],然后返回的数据帧nan的”。 if部分获取字典列表,并为每行创建一个微型数据框。
  4. 然后,我们使用下一部分连接这些小型词典,每行一个,并将它们连接到原始数据框。

我认为使用apply to your df将是一个选择。 首先,我将NaN替换为空列表:

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

如果类型为add_to_cart ,则创建一个add_to_cart函数以读取操作列表,并使用apply创建列:

def add_to_cart(list_action):
    for action in list_action:
        # for each action, see if the key action_type has the value add_to_cart and return the value
        if action['action_type'] == 'add_to_cart':
            return action['value']
    # if no add_to_cart action, then empty
    return ''

df['add_to_cart'] = df['actions'].apply(add_to_cart)

purchase相同的想法:

def purchase(list_action):
    for action in list_action:
        if action['action_type'] == 'purchase':
            return action['value']
    return ''

df['purchase'] = df['actions'].apply(purchase)

然后,您可以根据需要删除列actions

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

编辑:定义一个唯一的函数find_action ,然后apply一个参数,例如:

def find_action(list_action, action_type):
    for action in list_action:
        # for each action, see if the key action_type is the one wanted
        if action['action_type'] == action_type:
            return action['value']
    # if not the right action type found, then empty
    return ''
df['add_to_cart'] = df['actions'].apply(find_action, args=(['add_to_cart']))
df['purchase'] = df['actions'].apply(find_action, args=(['purchase']))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM