我有一个嵌套词典:
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
}
}
使用这个词典,我想创建一个与每个键相关联的数据帧字典,即2010
,2011
和2012
。我还想将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
我无法找到我做错的地方。我将不胜感激任何帮助。
答案 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