[英]Convert JSON with nested objects to Pandas Dataframe
I am trying to load json from a url and convert to a Pandas dataframe, so that the dataframe would look like the sample below. 我试图从URL加载json并将其转换为Pandas数据框,以便该数据框看起来像下面的示例。
I've tried json_normalize, but it duplicates the columns, one for each data type (value and stringValue). 我试过了json_normalize,但是它复制了列,每种数据类型(值和stringValue)一个。 Is there a simpler way than this method and then dropping and renaming columns after creating the dataframe? 有没有比此方法更简单的方法,然后在创建数据框后删除和重命名列? I want to keep the stringValue. 我想保留stringValue。
Person ID Position ID Job ID Manager
0 192 936 93 Tom
my_json = {
"columns": [
{
"alias": "c3",
"label": "Person ID",
"dataType": "integer"
},
{
"alias": "c36",
"label": "Position ID",
"dataType": "string"
},
{
"alias": "c40",
"label": "Job ID",
"dataType": "integer",
"entityType": "job"
},
{
"alias": "c19",
"label": "Manager",
"dataType": "integer"
},
],
"data": [
{
"c3": {
"value": 192,
"stringValue": "192"
},
"c36": {
"value": "936",
"stringValue": "936"
},
"c40": {
"value": 93,
"stringValue": "93"
},
"c19": {
"value": 12412453,
"stringValue": "Tom"
}
}
]
}
If c19 is of type string, this should work 如果c19是字符串类型,这应该可以工作
alias_to_label = {x['alias']: x['label'] for x in my_json["columns"]}
is_str = {x['alias']: ('string' == x['dataType']) for x in my_json["columns"]}
data = []
for x in my_json["data"]:
data.append({
k: v["stringValue" if is_str[k] else 'value']
for k, v in x.items()
})
df = pd.DataFrame(data).rename(columns=alias_to_label)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.