在本文中,我们将探讨如何使用 pandas 有效地操作具有嵌套对象的 JSON 数据结构。
考虑以下 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": ""
}
]
}
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_')
这会生成一个 DataFrame,其中包含嵌套“locations”对象中每个键的列。
如果不进行扁平化如果需要,您可以使用 Pandas 的分组和串联功能:
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()
此方法连接“locations” " 值作为“日期”、“名称”和“数字”的每个唯一组合的逗号分隔字符串。
通过利用 pandas 的 json_normalize 和分组/串联功能,我们可以有效地处理嵌套的 JSON 结构,使我们能够以表格格式提取和操作数据。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3