我正在尝试将json文件加载到pandas数据帧。 我发现有一些嵌套的json。 下面是示例json:
{'events': [{'id': 142896214,
'playerId': 37831,
'teamId': 3157,
'matchId': 2214569,
'matchPeriod': '1H',
'eventSec': 0.8935539999999946,
'eventId': 8,
'eventName': 'Pass',
'subEventId': 85,
'subEventName': 'Simple pass',
'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}],
'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}
我使用以下代码将json加载到dataframe中:
with open('EVENTS.json') as f:
jsonstr = json.load(f)
df = pd.io.json.json_normalize(jsonstr['events'])
下面是df.head()的输出
但是我发现了两个嵌套的列,比如positions和tags。
我试着用下面的代码来压平它:
Position_data = json_normalize(data =jsonstr['events'], record_path='positions', meta = ['x','y','x','y'] )
它告诉我一个错误如下:
KeyError: "Try running with errors='ignore' as key 'x' is not always present"
你能告诉我如何平展位置和标签(那些有嵌套数据的)。
谢谢, 泽普
创建数据帧
用
pd.Series
压平positions
重命名
positions[0]
&;positions[1]
:用
pd.Series
压平tags
:重命名
id
&;label
:将它们与
pd.concat
结合起来:删除旧列:
如果您正在寻找从json展开多个层次结构的更通用方法,那么可以使用
recursion
和列表理解来重塑数据。一个备选方案如下:然后可以应用于数据,而不受嵌套级别的影响:
新样本数据
用法
请注意,这个
flatten_json
代码不是我的,我已经看到它here和here没有太多原始源的确定性。相关问题 更多 >
编程相关推荐