缺少键时使用 json_normalize 函数

Using the json_normalize function when a key is missing

我遇到了 json_normalize 函数的问题。当为一个项目指定一个可能丢失的键时,它会抛出一个键错误。如您所见,listPeople 并不总是存在于文件中。

df = {'Links':[{'id' : 1,'Gender' : 'X'},
         {'id' : 2,'Gender' : 'Y','listPeople' : [{'Person':'John', 'Age' : 42}] }
         ]
        }
test = json_normalize(df, record_path= "listPeople", errors = "ignore")
print(test)

根据 documentation,使用 errors = "ignore" 应该可以解决问题,但这似乎不起作用?

预期输出:

Person   Age
  NULL  NULL
  John    42

errors = "ignore" 适用于缺少的字典键,但您缺少一个可能包含多个字典的列表,并且您希望将其作为 record_path 传递。您可以用空值填充缺失的 listPeople

[i.update({'listPeople':[{'Person':None,'Age':None}]}) for i in df['Links'] if 'listPeople' not in i.keys()]

test = pd.json_normalize(df['Links'], record_path=['listPeople'], meta=['id','Gender'], errors = "ignore")

结果:

Person Age id Gender
0 None NaN 1 X
1 John 42 2 Y