Use pandas.io.json.json_normalize
json_normalize(data,record_path=['teams','members'],meta=[['teams','teamname']])
output:
email firstname lastname mobile orgname phone teams.teamname
0 [email protected] John Doe Anon 916-555-1234 1
1 [email protected] Jane Doe 916-555-7890 Anon 916-555-4321 1
2 [email protected] Mickey Moose 916-555-1111 Moosers 916-555-0000 2
3 [email protected] Minny Moose Moosers 916-555-2222 2
解释
from pandas.io.json import json_normalize
import pandas as pd
我最近才学会如何使用 json_normalize 函数,所以我的解释可能不正确。
从我所说的“第 0 层”开始
json_normalize(data)
output:
teams
0 [{'teamname': '1', 'members': [{'firstname': '...
有 1 列和 1 行。一切都在“团队”栏中。
使用 record_path= 查看我所说的“第 1 层”
json_normalize(data,record_path='teams')
output:
members teamname
0 [{'firstname': 'John', 'lastname': 'Doe', 'org... 1
1 [{'firstname': 'Mickey', 'lastname': 'Moose', ... 2
在第 1 层中,我们已扁平化“团队名称”,但内部有更多“成员”。
使用 record_path= 查看第 2 层。这个符号一开始并不直观。我现在通过 ['layer','deeperlayer'] 记住它,结果是layer.deeperlayer。
json_normalize(data,record_path=['teams','members'])
output:
email firstname lastname mobile orgname phone
0 [email protected] John Doe Anon 916-555-1234
1 [email protected] Jane Doe 916-555-7890 Anon 916-555-4321
2 [email protected] Mickey Moose 916-555-1111 Moosers 916-555-0000
3 [email protected] Minny Moose Moosers 916-555-2222
请原谅我的输出,我不知道如何在响应中制作表格。
最后我们使用 meta= 添加第 1 层列
json_normalize(data,record_path=['teams','members'],meta=[['teams','teamname']])
output:
email firstname lastname mobile orgname phone teams.teamname
0 [email protected] John Doe Anon 916-555-1234 1
1 [email protected] Jane Doe 916-555-7890 Anon 916-555-4321 1
2 [email protected] Mickey Moose 916-555-1111 Moosers 916-555-0000 2
3 [email protected] Minny Moose Moosers 916-555-2222 2
请注意,我们如何需要 meta=[[]] 的列表列表来引用第 1 层。
如果我们想要第 0 层和第 1 层中的一列,我们可以这样做:
json_normalize(data,record_path=['layer1','layer2'],meta=['layer0',['layer0','layer1']])
json_normalize 的结果是 pandas 数据帧。