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

时间:2018-07-07 03:10:20

标签: python python-3.x list dictionary dataframe

我有一个要转换为数据框的列表。 我在名为data的变量中大约有30000个列表。我如何将其转换为具有列属性,product_id,description,ustomer_id和country的数据框。我希望将元素属性转换为数据框

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)

,但是它只给出了两列,例如“事件”和“属性”。我希望属性形成一个数据框

2 个答案:

答案 0 :(得分:1)

使用小的示例集:

>>> 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'}}]

您可以简单地使用生成器表达式将dict调整为适当的形式:

>>> 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

答案 1 :(得分:0)

您也可以这样做:

from pandas.io.json import json_normalize
import pandas as pd
resultDf = pd.DataFrame()

for dictionary in data:
    for key, value in dictionary.items():

        if key == 'properties':
            df = json_normalize(value)
            resultDf = resultDf.append(df)

print(resultDf) 给出:

  country  customer_id description invoice_no product_id
0      US           55       cloth         44         67
1   China           23        shoe         55         66