[英]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.