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

标签 python pandas list dataframe dictionary

我有一个列表,我想将其转换为数据帧。 我在名为 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/

相关文章:

Python Pandas : fill a dataframe row by row

python - Pandas/SQLalchemy 合并数据框和表

python - 如何在 Python 中打印对象的列表、字典或集合

python - 无法在 python 中读取 stata .dta 文件

python - 在 Python 中初始化一个固定大小的数组

javascript - SharePoint 在单击时传递文本框的值以更新列表列

python - 为什么我们在 tensorflow 的损失函数中需要 `int64` 作为 MNIST 标签?

python - Django 条件创建

python - 在 Git Bash 中启动 Python 脚本

python - 我可以禁用 mutmut 中的字符串突变吗?