我正在接收以下格式的請求(我無法更改輸入請求格式):
{ "inputs":
[
{
"TimeGenerated": "datetimestring",
"counters": {
"counter1": float_value,
"counter2": float_value,
"counter3": float_value
}
},
{
"TimeGenerated": "datetimestring",
"counters": {
"counter1": float_value,
"counter2": float_value,
"counter3": float_value
}
},
{
"TimeGenerated": "datetimestring",
"counters": {
"counter1": float_value,
"counter2": float_value,
"counter3": float_value
}
}
]
}
我想用DataFrame這個字典創建一個列:TimeGenerated, counter1, counter2, counter3。
DataFrame從這個嵌套字典串列中創建一個最有效的pythonic方法是什么?
可能的解決方案(不是最有效的一個)
我發現的解決方案是:
x = []
for i in input_json['inputs']:
counters = i['counters'] # We do not want counters in the column headers. This returns the dictionary { "counter1": float_value, "counter2": float_value, "counter3": float_value}
counters['_time'] = i['TimeGenerated'] # The idea to extract it and then add it to the common dictionary. Counters would now be like { "counter1": float_value, "counter2": float_value, "counter3": float_value, "_time": "datetimestring"}
x.append(counters) # Create a list of such dictionaries (with single level dictionaries without any nesting)
in_df = pd.DataFrame(x) # Create a Dataframe from the list
in_df['_time'] = pd.to_datetime(in_df['_time']) # To convert datetimestring to datetime.
但是,我相信有更有效的方法可以實作這一目標!
類似的問題(具有不同的預期最終結果)
StackOverflow 上的一些其他問題解決了類似的問題(但預計會有不同的結果)。添加它們以供在實際搜索另一個最終結果時偶然發現的人細讀(此外,將作為一個很好的比較點來使用 Python 字典、串列和資料幀以及它們是如何相互關聯的)。
- Python Dataframe 包含一個字典串列,需要用字典項創建新的資料框
- 從嵌套字典創建熊貓資料框,外鍵作為 df 索引和內鍵列標題
- 從嵌套字典創建資料框
uj5u.com熱心網友回復:
假設所有子物件具有相同的結構,您可以從第一個列出鍵并將它們用于列。
columns = ['TimeGenerated', *j['inputs'][0]['counters'].keys()]
df = pd.DataFrame([[t['TimeGenerated'], *t['counters'].values()] for t in j['inputs']], columns=columns)
輸出
>>> df
TimeGenerated counter1 counter2 counter3
0 datetimestring 123.456 123.456 123.456
1 datetimestring 123.456 123.456 123.456
2 datetimestring 123.456 123.456 123.456
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358207.html
下一篇:尋找最常見的元素
