[英]Pandas read nested json
我很好奇如何使用 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
构造函数和最后一个groupby
使用带有解析name
的DataFrame
和 apply 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...
pandas.json_normalize
的一种可能替代方法是通过仅从嵌套字典中提取选定的键和值来构建您自己的 dataframe。 这样做的主要原因是 json_normalize 对于非常大的 json 文件会变慢(并且可能并不总是产生您想要的 output)。
因此,这是使用glom
展平 pandas 中的嵌套字典的另一种方法。 目的是从嵌套字典中提取选定的键和值,并将它们保存在 pandas dataframe 的单独列中(:
这是一步一步的指南: https://medium.com/@enrico.alemani/flatten-nested-dictionaries-in-pandas-using-glom-7948345c88f5
import pandas as pd from glom import glom from ast import literal_eval target = { "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" } } # Import data df = pd.DataFrame([str(target)], columns=['target']) # Extract id keys and save value into a separate pandas column df['id'] = df['target'].apply(lambda row: glom(literal_eval(row), 'locations.name'))
如果有人发现这个,另一个选择,因为我正在通过笔记本工作。 用 df 读取文件
df = pd.read_json('filename.json')
df2 = pd.DataFrame.from_records(df['nest_level_1']['nest_level_2'])
快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.