gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:29:05 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com