【问题标题】:Convert list of dictionaries into dataframe python将字典列表转换为数据框python
【发布时间】:2018-07-07 03:10:20
【问题描述】:

我有一个想要转换为数据框的列表。 我在一个名为 data 的变量中有大约 30000 个列表。如何将其转换为具有列属性、产品 ID、描述、客户 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)

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 2019-04-21
        • 2014-06-12
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多