Python 熊猫:在单独的列中显示嵌套的字典值
我有一个类似这样的字典列表Python 熊猫:在单独的列中显示嵌套的字典值,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个类似这样的字典列表 [ { "detail": { "name": "boo", "id": 1 }, "other": { "gender": "m", "no": "234" } }, { "detail": { "name": "hoo", "id": 2 }, "other": { "gender": "f", "no": "
[
{
"detail": {
"name": "boo",
"id": 1
},
"other": {
"gender": "m",
"no": "234"
}
},
{
"detail": {
"name": "hoo",
"id": 2
},
"other": {
"gender": "f",
"no": "456"
}
}
]
我想以以下格式将这些数据打印到excel文件中
detail other
name id gender no
boo 1 m 234
hoo 2 f 456
简而言之,我想在父键列下的列中显示嵌套值。我如何使用熊猫来实现这一点
或者是他们的任何其他图书馆,通过它我可以做到这一点,因为熊猫是安静沉重的一个 使用
pd.io.json.json\u规范化
df = pd.io.json.json_normalize(data)
i = list(map(tuple, df.columns.str.split('.')))
这将导致列名如下所示-
df.columns
Index(['detail.id', 'detail.name', 'other.gender', 'other.no'], dtype='object')
我们需要使用df.columns.str.split
-
df = pd.io.json.json_normalize(data)
i = list(map(tuple, df.columns.str.split('.')))
调用pd.MultiIndex.from_tuples
并将结果分配回-
df.columns = pd.MultiIndex.from_tuples(i)
df
detail other
id name gender no
0 1 boo m 234
1 2 hoo f 456
如果您的数据更复杂,您可能需要对以下列进行额外的sort\u index
调用-
df = df.sort_index(axis=1)
尼西。。。非常感谢你。