[英]how do you convert json output to a data frame in python
我需要將此 json 文件轉換為 python 中的數據幀:
print(resp2)
{
"totalCount": 1,
"nextPageKey": null,
"result": [
{
"metricId": "builtin:tech.generic.cpu.usage",
"data": [
{
"dimensions": [
"process_345678"
],
"dimensionMap": {
"dt.entity.process_group_instance": "process_345678"
},
"timestamps": [
1642021200000,
1642024800000,
1642028400000
],
"values": [
10,
15,
12
]
}
]
}
]
}
Output 需要是這樣的:
metricId dimensions timestamps values
builtin:tech.generic.cpu.usage process_345678 1642021200000 10
builtin:tech.generic.cpu.usage process_345678 1642024800000 15
builtin:tech.generic.cpu.usage process_345678 1642028400000 12
我試過這個:
print(pd.json_normalize(resp2, "data"))
我得到無效的語法,有什么想法嗎?
查看json_normalize
的示例,您將看到一個字典列表,其中包含您想要的列的鍵名,每一行都是唯一的。 當您有嵌套列表/對象時,列將被展平以具有點符號,但嵌套的 arrays 最終不會跨行重復。
因此,將數據解析為平面列表,然后您可以使用from_records
。
data = []
for r in resp2['result']:
metricId = r['metricId']
for d in r['data']:
dimension = d['dimensions'][0] # unclear why this is an array
timestamps = d['timestamps']
values = d['values']
for t, v in zip(timestamps, values):
data.append({'metricId': metricId, 'dimensions': dimension, 'timestamps': t, 'values': v})
df = pd.DataFrame.from_records(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.