使用json中的特定值填充pandas数据帧

时间:2016-02-24 17:44:08

标签: python json pandas iteration dataframe

我有一个非常大的,深度嵌套的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]索引:   []

为什么这个方法是空的,以及如何正确填充它?

1 个答案:

答案 0 :(得分:0)

如果您只是尝试向数据框添加单行,则可以使用

df = df.append({"groupe":group,"id":id,"MotherName":MotherName,"FatherName":FatherName},
                ignore_index=True)