gpt4 book ai didi

python - Pandas 读取嵌套的 json

转载 作者:IT老高 更新时间:2023-10-28 21:10:21 25 4
gpt4 key购买 nike

我很好奇如何使用 pandas 读取以下结构的嵌套 json:

{
"number": "",
"date": "01.10.2016",
"name": "R 3932",
"locations": [
{
"depTimeDiffMin": "0",
"name": "Spital am Pyhrn Bahnhof",
"arrTime": "",
"depTime": "06:32",
"platform": "2",
"stationIdx": "0",
"arrTimeDiffMin": "",
"track": "R 3932"
},
{
"depTimeDiffMin": "0",
"name": "Windischgarsten Bahnhof",
"arrTime": "06:37",
"depTime": "06:40",
"platform": "2",
"stationIdx": "1",
"arrTimeDiffMin": "1",
"track": ""
},
{
"depTimeDiffMin": "",
"name": "Linz/Donau Hbf",
"arrTime": "08:24",
"depTime": "",
"platform": "1A-B",
"stationIdx": "22",
"arrTimeDiffMin": "1",
"track": ""
}
]
}

这里将数组保存为 json。我宁愿把它展开成列。

pd.read_json("/myJson.json", orient='records')

编辑

感谢您的第一个答案。我应该完善我的问题:数组中嵌套属性的展平不是强制性的。只需 [A, B, C] 连接 df.locations['name'] 就可以了。

我的文件包含多个 JSON 对象(每行 1 个)我想保留数字、日期、名称和位置列。但是,我需要加入这些位置。

allLocations = ""
isFirst = True
for location in result.locations:
if isFirst:
isFirst = False
allLocations = location['name']
else:
allLocations += "; " + location['name']
allLocations

我这里的方法似乎效率不高/ Pandas 风格。

最佳答案

您可以使用 json_normalize :

import json

with open('myJson.json') as data_file:
data = json.load(data_file)

df = pd.json_normalize(data, 'locations', ['date', 'number', 'name'],
record_prefix='locations_')
print (df)
locations_arrTime locations_arrTimeDiffMin locations_depTime \
0 06:32
1 06:37 1 06:40
2 08:24 1

locations_depTimeDiffMin locations_name locations_platform \
0 0 Spital am Pyhrn Bahnhof 2
1 0 Windischgarsten Bahnhof 2
2 Linz/Donau Hbf 1A-B

locations_stationIdx locations_track number name date
0 0 R 3932 R 3932 01.10.2016
1 1 R 3932 01.10.2016
2 22 R 3932 01.10.2016

编辑:

您可以使用 read_json通过 DataFrame 构造函数和最后 groupby 解析 name与应用 join:

df = pd.read_json("myJson.json")
df.locations = pd.DataFrame(df.locations.values.tolist())['name']
df = df.groupby(['date','name','number'])['locations'].apply(','.join).reset_index()
print (df)
date name number locations
0 2016-01-10 R 3932 Spital am Pyhrn Bahnhof,Windischgarsten Bahnho...

关于python - Pandas 读取嵌套的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40588852/

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