gpt4 book ai didi

python - 将字典列表转换为数据框python

转载 作者:行者123 更新时间:2023-12-01 09:16:23 27 4
gpt4 key购买 nike

我有一个列表,我想将其转换为数据帧。我在名为 data 的变量中有大约 30000 个列表。我如何将其转换为包含列属性、product_id、description、ustomer_id 和国家/地区的数据框。我希望将元素属性转换为数据框

data[0]
Out[16]:
{'event': 'Product',
'properties': {'invoice_no': '44',
'product_id': '67',
'description': 'cloth',
'customer_id': 55,
'country': 'US'}}


data[1]
Out[17]:
{'event': 'Product',
'properties': {'invoice_no': '55',
'product_id': '66',
'description': 'shoe',
'customer_id': 23,
'country': 'China'}}

尝试过这个,

new = pd.DataFrame.from_dict(data)

但它只提供了两列,例如“事件”和“属性”。我希望属性形成数据框

最佳答案

使用您的小示例集:

>>> from pprint import pprint
>>> pprint(data)
[{'event': 'Product',
'properties': {'country': 'US',
'customer_id': 55,
'description': 'cloth',
'invoice_no': '44',
'product_id': '67'}},
{'event': 'Product',
'properties': {'country': 'China',
'customer_id': 23,
'description': 'shoe',
'invoice_no': '55',
'product_id': '66'}}]

您可以简单地使用生成器表达式将您的字典转换成适当的形式:

>>> pd.DataFrame(d['properties'] for d in data)
country customer_id description invoice_no product_id
0 US 55 cloth 44 67
1 China 23 shoe 55 66

关于python - 将字典列表转换为数据框python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219581/

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