Python 将字典传输到数据帧?

Python 将字典传输到数据帧?,python,pandas,Python,Pandas,我有下面的字典,我怎样才能把它转换成一个四列数据框?(列=[‘国家’、‘日期’、‘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 -

我有下面的字典,我怎样才能把它转换成一个四列数据框?(列=[‘国家’、‘日期’、‘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)。两者都返回错误。

您的字典似乎将数据帧作为值。如果是这种情况,将字典简化为数据帧的一种方法是循环字典,为每个子字典创建一个新列并连接它们:

import pandas as pd
df = pd.DataFrame()
for k, v in temp.items():
    v['country'] = k
    df = pd.concat([df, v])
一个类似的例子:

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}

temp    
#{'x':    a  b
# 0  1  2
# 1  2  3
# 2  3  4, 'y':    a  b
# 0  2  5
# 1  4  6
# 2  5  8}
其中:

df.reset_index()

#   a   b   country
#0  1   2   x
#1  2   3   x
#2  3   4   x
#3  2   5   y
#4  4   6   y
#5  5   8   y
您可以与和一起使用
重命名

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
另一个具有设置索引名称的解决方案(在
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