我目前正在尝试编辑来自 Mongo DB 的数据。我已经能够将数据读入数据帧。但是,我有一个问题,即在数据框中,一列包含一个字典列表。我已经尝试使用 pd.json.normalize 编辑数据,但我收到错误“浮动”对象没有属性“值”。如何将列转换为新的数据框?
数据框看起来像这样:
状态 | 消息 | 变量 |
---|---|---|
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'
答案 0 :(得分:0)
IIUC 使用:
df3 = pd.json_normalize(df3['vars'].dropna())