我有以下字典,如何将其转换为四列DataFrame?(列= ['country','date','2y','10y']
temp
{'Germany': date 2y 10y
0 2004-02-01 2.47 4.22
1 2004-03-01 2.22 4.05
2 2004-04-01 2.20 3.96
.. ... ... ...
149 2016-07-01 -0.65 -0.13
[150 rows x 3 columns], 'Japan': date 2y 10y
0 2004-02-01 0.07 1.32
1 2004-03-01 0.05 1.26
2 2004-04-01 0.10 1.42
.. ... ... ...
148 2016-06-01 -0.24 -0.12
149 2016-07-01 -0.33 -0.25
type(temp)
dict
我已经尝试过pd.DataFrame(temp)和pd.DataFrame.from_dict(temp)。两者均返回错误。
您可以concat
与reset_index
和一起使用rename
:
df1 = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4]})
df2 = pd.DataFrame({'a': [2,4,5], 'b': [5,6,8]})
temp = {'x': df1, 'y': df2}
print (temp)
print (pd.concat(temp)
.reset_index(level=1,drop=True)
.reset_index()
.rename(columns={'index':'country'}))
country a b
0 x 1 2
1 x 2 3
2 x 3 4
3 y 2 5
4 y 4 6
5 y 5 8
设置索引名称为rename_axis
(的新方法pandas
0.18.0
)的另一个解决方案:
print (pd.concat(temp)
.rename_axis(('country','temp'))
.reset_index(level=1,drop=True)
.reset_index())
country a b
0 x 1 2
1 x 2 3
2 x 3 4
3 y 2 5
4 y 4 6
5 y 5 8
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句