Pandas json_normalize erzeugt eine verwirrende `KeyError` Nachricht?
Ich versuche, einen verschachtelten JSON in einen Pandas-Datenrahmen zu konvertieren. Ich benutzejson_normalize
mit Erfolg, bis ich auf eine bestimmte JSON stieß. Ich habe eine kleinere Version davon erstellt, um das Problem zu beheben.
from pandas.io.json import json_normalize
json=[{"events": [{"schedule": {"date": "2015-08-27",
"location": {"building": "BDC", "floor": 5},
"ID": 815},
"group": "A"},
{"schedule": {"date": "2015-08-27",
"location": {"building": "BDC", "floor": 5},
"ID": 816},
"group": "A"}]}]
Ich führe dann aus:
json_normalize(json[0],'events',[['schedule','date'],['schedule','location','building'],['schedule','location','floor']])
Ich erwarte, so etwas zu sehen:
ID group schedule.date schedule.location.building schedule.location.floor
'815' 'A' '2015-08-27' 'BDC' 5
'816' 'A' '2015-08-27' 'BDC' 5
Aber stattdessen erhalte ich diesen Fehler:
In [2]: json_normalize(json[0],'events',[['schedule','date'],['schedule','location','building'],['schedule','location','floor']])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-2-b588a9e3ef1d> in <module>()
----> 1 json_normalize(json[0],'events',[['schedule','date'],['schedule','location','building'],['schedule','location','floor']])
/Users/logan/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/io/json.pyc in json_normalize(data, record_path, meta, meta_prefix, record_prefix)
739 records.extend(recs)
740
--> 741 _recursive_extract(data, record_path, {}, level=0)
742
743 result = DataFrame(records)
/Users/logan/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/io/json.pyc in _recursive_extract(data, path, seen_meta, level)
734 meta_val = seen_meta[key]
735 else:
--> 736 meta_val = _pull_field(obj, val[level:])
737 meta_vals[key].append(meta_val)
738
/Users/logan/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/io/json.pyc in _pull_field(js, spec)
674 if isinstance(spec, list):
675 for field in spec:
--> 676 result = result[field]
677 else:
678 result = result[spec]
KeyError: 'schedule'