[英]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.