【问题标题】:Pandas normalize list of dictsPandas 规范化字典列表
【发布时间】:2021-07-11 09:57:25
【问题描述】:

我目前正在尝试编辑 Mongo DB 中的数据。我已经能够将数据读入数据框中。但是,我有一个问题,即在数据框中,一列包含一个字典列表。我已经尝试使用 pd.json.normalize 编辑数据,但我得到错误'float' object has no attributes 'values'。如何将列转换为新的数据框?

数据框如下所示:

status message vars
1. ok [{'key': 'A1', 'value': '1', 'vartype: '1'}, {'key': 'A2', 'value': '0', 'vartype: '1'}, {'key': 'A3', 'value': '1', 'vartype: '1]

执行此行时,我收到以下错误消息:

df3 = pd.json_normalize(df3['vars'])
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-164-da47e4ddf140> in <module>
----> 1 df3 = pd.json_normalize(df3['vars'])

/opt/conda/lib/python3.8/site-packages/pandas/io/json/_normalize.py in _json_normalize(data, record_path, meta, meta_prefix, record_prefix, errors, sep, max_level)
    268 
    269     if record_path is None:
--> 270         if any([isinstance(x, dict) for x in y.values()] for y in data):
    271             # naive normalization, this is idempotent for flat records
    272             # and potentially will inflate the data considerably for

/opt/conda/lib/python3.8/site-packages/pandas/io/json/_normalize.py in <genexpr>(.0)
    268 
    269     if record_path is None:
--> 270         if any([isinstance(x, dict) for x in y.values()] for y in data):
    271             # naive normalization, this is idempotent for flat records
    272             # and potentially will inflate the data considerably for

AttributeError: 'float' object has no attribute 'values'

【问题讨论】:

    标签: python pandas pymongo


    【解决方案1】:

    IIUC 使用:

    df3 = pd.json_normalize(df3['vars'].dropna())
    

    【讨论】:

    • 我不断收到:AttributeError: 'list' object has no attribute 'values'
    • @SyrixGG - import jsondf3 = pd.json_normalize(df3['vars'].apply(json.loads)) 的工作情况如何?
    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 2020-12-11
    • 2016-06-09
    • 1970-01-01
    • 2020-12-31
    • 2013-05-30
    • 1970-01-01
    • 2012-08-21
    相关资源
    最近更新 更多