gpt4 book ai didi

python - 使用 json_normalize 从多个级别获取元值

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:01 24 4
gpt4 key购买 nike

假设这是我的 JSON:

ds = [{
"name": "groupa",
"subGroups": [{
"subGroup": 1,
"people": [{
"firstname":"Tony",
},
{
"firstname":"Brian"
}
]
}]
},
{
"name": "groupb",
"subGroups": [{
"subGroup": 1,
"people": [{
"firstname":"Tony",
},
{
"firstname":"Brian"
}
]
}]
}
]

我通过以下方式创建数据框:

df = json_normalize(ds, record_path =['subGroups', 'people'], meta=['name'])

这给了我:

    firstname   name
0 Tony groupa
1 Brian groupa
2 Tony groupb
3 Brian groupb

但是,我还想包括 subGroup 列。

我尝试:

df = json_normalize(ds, record_path =['subGroups', 'people'], meta=['name', 'subGroup'])

但这给出了:

KeyError: 'subGroup'

有什么想法吗?

最佳答案

json_normalize(
ds,
record_path=['subGroups', 'people'],
meta=[
'name',
['subGroups', 'subGroup'] # each meta field needs its own path
],
errors='ignore'
)

firstname name subGroups.subGroup
0 Tony groupa 1
1 Brian groupa 1
2 Tony groupb 1
3 Brian groupb 1

关于python - 使用 json_normalize 从多个级别获取元值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49411190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com