从pandas中的字典字典制作数据帧字典

时间:2017-06-11 09:50:50

标签: python pandas dictionary dataframe

我有一个嵌套词典:

    Night_interval={
    '2010': {
      Timestamp('2010-07-01 00:00:00'): 29,
      Timestamp('2010-07-02 00:00:00'): 28,
      Timestamp('2010-07-03 00:00:00'): 28,
      Timestamp('2010-07-04 00:00:00'): 29,
      Timestamp('2010-07-05 00:00:00'): 28
            },
    '2011': {
      Timestamp('2010-07-01 00:00:00'): 29,
      Timestamp('2010-07-02 00:00:00'): 28,
      Timestamp('2010-07-03 00:00:00'): 28,
      Timestamp('2010-07-04 00:00:00'): 29,
      Timestamp('2010-07-05 00:00:00'): 28
            },
    '2012': {
      Timestamp('2010-07-01 00:00:00'): 29,
      Timestamp('2010-07-02 00:00:00'): 28,
      Timestamp('2010-07-03 00:00:00'): 28,
      Timestamp('2010-07-04 00:00:00'): 29,
      Timestamp('2010-07-05 00:00:00'): 28
            }
  }

使用这个词典,我想创建一个与每个键相关联的数据帧字典,即201020112012。我还想将Timestamp作为每个数据帧中的索引。我尝试编写以下代码:

Years = ['2010','2011','2012']
for key in Years:
    df_interval[key] = pd.DataFrame(Night_interval[key]) 

但是,我收到此错误: ValueError: If using all scalar values, you must pass an index

我无法找到我做错的地方。我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:1)

如果需要dict,请使用列名为DataFrame的构造函数:

df_interval = {}
Years = ['2010','2011','2012']
for key in Years:
    df_interval[key] = pd.DataFrame({key:Night_interval[key]})

print (df_interval['2012'])
            2012
2010-07-01    29
2010-07-02    28
2010-07-03    28
2010-07-04    29
2010-07-05    28
df_interval = {}
Years = ['2010','2011','2012']
for key in Years:
    df_interval[key] = pd.DataFrame({'a':Night_interval[key]})

print (df_interval['2012'])
             a
2010-07-01  29
2010-07-02  28
2010-07-03  28
2010-07-04  29
2010-07-05  28

如果只有一列可以创建dict的{​​{1}}:

Series