PAs*_*loE 4 python dictionary dataframe pandas
我正在尝试将以下字典转换为 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}}
Run Code Online (Sandbox Code Playgroud)
我需要得到一个如下所示的结果数据框:
Sector 1965 1966 1967
1 52 34 56
2 54 34 56
3 67 35 54
4 45 76 34
Run Code Online (Sandbox Code Playgroud)
我正在使用这样的东西,但我没有得到我需要的结果。
df = pd.DataFrame([[col1,col2,col3] for col1, d in test.items() for col2, col3 in d.items()])enter code here
Run Code Online (Sandbox Code Playgroud)
非常感谢你的帮助!!!
您可以使用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
Run Code Online (Sandbox Code Playgroud)