[英]Convert dictionary of dictionaries into DataFrame Python
我正在嘗試將以下詞典的字典轉換為pandas DataFrame。
我的字典看起來像這樣:
mydata = {1965:{1:52, 2:54, 3:67, 4:45},
1966:{1:34, 2:34, 3:35, 4:76},
1967:{1:56, 2:56, 3:54, 4:34}}
我需要得到一個看起來像這樣的結果數據框:
Sector 1965 1966 1967
1 52 34 56
2 54 34 56
3 67 35 54
4 45 76 34
我正在使用類似的東西,但沒有得到所需的結果。
df = pd.DataFrame([[col1,col2,col3] for col1, d in test.items() for col2, col3 in d.items()])enter code here
非常感謝你的幫助!!!
您可以使用DataFrame.from_records
:
import pandas as pd
ydata = {1965:{1:52, 2:54, 3:67, 4:45},
1966:{1:34, 2:34, 3:35, 4:76},
1967:{1:56, 2:56, 3:54, 4:34}}
print (pd.DataFrame.from_records(ydata))
1965 1966 1967
1 52 34 56
2 54 34 56
3 67 35 54
4 45 76 34
print (pd.DataFrame.from_records(ydata).reset_index().rename(columns={'index':'Sector'}))
Sector 1965 1966 1967
0 1 52 34 56
1 2 54 34 56
2 3 67 35 54
3 4 45 76 34
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.