从具有嵌套字典的字典列表中创建DataFrame

2024-03-28 10:02:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我以JSON格式从API中检索数据,并希望从中创建一个pandas数据帧。我要分析的内容是一个字典列表,其中的字典不一定具有相同的键,其中一些还包括嵌套字典。你知道吗

现在我已经得到了一个非常接近我想要的结果,但是我得到了一个我想要克服的警告(实际上有几个使用原始数据):

...\pandas\indexes\api.py:37: RuntimeWarning: unorderable types: int() < str(), sort order is undefined for incomparable objects union = _union_indexes(indexes)

我正在Windows 10上使用Python 3.4.2,这个MWE应该可以说明我的问题:

import pandas as pd
import json

content = [{"Id": "A1", "SomeInfo": 0, "description": "Lorem Ipsum, lorem ipsum."},
       {"Id": "B2", "SomeInfo": 2, "otherInfo": 0, "nestedInfo": {"inf1": 3, "inf2": 3}},
       {"Id": "C3", "SomeInfo": 2, "nestedInfo": {"inf1": 3, "inf3": 2}}]

content = pd.DataFrame(content)

df = pd.concat([content.drop(['nestedInfo'], axis=1), content['nestedInfo'].apply(pd.Series)], axis=1)

我想要的结果最好是这样:

   Id  SomeInfo                description  otherInfo   inf1  inf2  inf3
0  A1         0  Lorem Ipsum, lorem ipsum.        NaN   NaN   NaN   NaN
1  B2         2                        NaN        0     3     3     NaN
2  C3         2                        NaN        NaN   3     NaN   2

如有任何关于如何改善上述问题的建议或更好的解决方案,我们将不胜感激。你知道吗


Tags: 数据importidpandas字典a1descriptioncontent