【问题标题】:TypeError when convert list of dictionaries to a DataFrame将字典列表转换为 DataFrame 时出现 TypeError
【发布时间】:2021-07-24 05:43:23
【问题描述】:

我有 a_list

[{
    'attributes': {
        'title': 'apple',
        'id': '5543',
        'owner': 'tom',
    }
},
{
    'attributes': {
        'title': 'pear',
        'id': '5432',
        'owner': 'suzy',
    }
},
{
    'attributes': {
        'title': 'orange',
        'id': '1234',
        'owner': 'james',
    }
}]

我试图将其作为一个简单的数据框返回。

通过查看其他帖子,嵌套字典让我认为我应该使用 json_normalize 并传入 record_path 的属性。

df = pd.json_normalize(a_list, record_path='attributes', meta= ['title', 'id', 'owner'])

但是,这会返回一个异常:

TypeError: {'attributes': {'title': 'apple', 'id': '5543', 'owner': 'tom'}} has non list value {'title': 'apple', 'id': '5543', 'owner': 'tom'} for path attributes. Must be list or null.

我在这里做错了什么?

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    您可以使用简单的列表推导:

    df = pd.DataFrame([d["attributes"] for d in lst])
    print(df)
    

    打印:

        title    id  owner
    0   apple  5543    tom
    1    pear  5432   suzy
    2  orange  1234  james
    

    【讨论】:

      猜你喜欢
      • 2014-01-05
      • 2021-11-28
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多