用json中的特定值填充pandas dataframe

2024-10-03 11:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常大、嵌套很深的json,从中我只需要一些键值对,而不是全部。因为它的嵌套非常深,直接从json创建pandas数据帧是不舒服的,因为我需要的所有值都不在列中。在

我需要创建pandas数据帧,它应该看起来像:

^{1}$

从我复杂的json中,我提取了我需要的值,如下所示(所有值都被正确提取,因此这里没有错误):

^{pr2}$

jfile看起来像:

{"location":{"town":"Rome","groupe":"Advanced", "school":{"SchoolGroupe":"TrowMet", "SchoolName":"VeronM"}}, "id":"145", "Mother":{"MotherName":"Helen","MotherAge":"46"},"NGlobalNote":2, "Father":{"FatherName":"Peter","FatherAge":"51"}, "Teacher":["MrCrock","MrDaniel"],"Field":"Marketing","season":["summer","spring"]}

然后我创建一个空的数据帧并尝试用以下值填充它:

df=pd.DataFrame(columns=['group', 'id', 'Father', 'Mother'])
for index,row in df.iterrows():
    row['groupe']=jfile['location']['groupe']
    row['id']=jfile['id']
    row['MotherName']=jfile['Father']['FatherName']
    row['id']=jfile['Mother']['MotherName']

但当我试图打印它时,它显示数据框是空的:

Empty DataFrame Columns: [groupe, id, MotherName, FatherName] Index: []

为什么这个方法是空的,我如何才能正确地填充它?在


Tags: 数据idjsondataframepandasdflocation键值