[英]Fill pandas dataframe with specific values from json
我有一个很大的,深度嵌套的json,从中我只需要一些键值对,而不是全部。 因为它的嵌套非常深,所以直接从json创建一个pandas数据帧并不方便,因为我需要的所有值都不会在列中。
我需要创建应该如下所示的pandas数据框:
Groupe Id MotherName FatherName
Advanced 56 Laure James
Middle 11 Ann Nicolas
Advanced 6 Helen Franc
从我的复杂json中,我提取所需的值,如下所示(所有值均已正确提取,因此这里没有错误):
jfile=json.loads(data)
groupe=jfile['location']['groupe']
id=jfile['id']
MotherName=jfile['Mother']['MotherName']
FatherName=jfile['Father']['FatherName']
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']
但是当我尝试打印它时,它说数据框为空:
空的DataFrame列:[groupe,id,MotherName,FatherName]索引:[]
为什么用这种方法是空的,如何正确填充它?
如果您只是想在数据框中添加一行,则可以使用
df = df.append({"groupe":group,"id":id,"MotherName":MotherName,"FatherName":FatherName},
ignore_index=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.