[英]json normalize to Dataframe for nested objects, Python
我正在尝试使用规范化 function 将 json 转换为使用 json_normalize 的数据帧。 这是我正在使用的 json
data = {
"Parent":
[
{
"Attributes":
[
{
"Values": [{
"Month": "Jan",
"Value": "100"
}],
"Id": "90",
"CustId": "3"
},
{
"Values": [{
"Month": "Jan",
"Value": "101"
}],
"Id": "88"
},
{
"Values": [{
"Month": "Jan",
"Value": "102"
}],
"Id": "89"
}
],
"DId": "1234"
},
{
"Attributes":
[
{
"Values": [{
"Month": "Jan",
"Value": "200"
}],
"Id": "90",
"CustId": "3"
},
{
"Values": [{
"Month": "Jan",
"Value": "201"
}],
"Id": "88"
},
{
"Values": [{
"Month": "Jan",
"Value": "202"
}],
"Id": "89"
}
],
"DId": "5678"
}
]
}
这就是我试过的
print(type(data))
result = pd.json_normalize(data, record_path=['Parent',['Attributes']], max_level=2)
print(result.to_string())
这就是我想要实现的
任何如何完成它的指导将不胜感激。
您可以通过meta
关键字参数指定元数据( record_path
上方的数据)(结合errors='ignore'
用于不一定存在的元数据,如CustId
)。 例如
result = pd.json_normalize(
data,
record_path=['Parent', 'Attributes', 'Values'],
meta=[
['Parent', 'DId'],
['Parent', 'Attributes', 'Id'],
['Parent', 'Attributes', 'CustId']
],
errors='ignore'
)
结果是
Month Value Parent.DId Parent.Attributes.Id Parent.Attributes.CustId
0 Jan 100 1234 90 3
1 Jan 101 1234 88 NaN
2 Jan 102 1234 89 NaN
3 Jan 200 5678 90 3
4 Jan 201 5678 88 NaN
5 Jan 202 5678 89 NaN
这是实现这一目标的一种方法,我认为 step1 和 step2 可以组合在一起,这需要对pd.json_normalize
有更多的了解
#step1
df1=pd.json_normalize(
data['Parent'],["Attributes","Values"]
)
#step2
df2=pd.json_normalize(
data['Parent'],"Attributes","DId",
)
df2=df2.drop(['Values'], axis=1)
result=df2.join(df1).reindex(['DId','Id','CustId','Month','Value'], axis=1)\
.sort_values(by=['DId','Id']) \
.rename(columns={'Id':'Attr.Id','CustId':'Attr.CustId','Month':'Attr.Values.Month',
'Value':'Attr.Values.value'
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.