2017-12-18 63 views
1

我有一个名为time的datetime列的Pandas数据框。我想计算每小时的行数。问题是,我希望生成的表格处理几小时不存在行。例如:将缺失的数据添加到按日期分组的数据框中

time id lat lon type 
0 2017-06-09 19:34:59.945128-07:00 75 36.999866 -122.058180 UPPER CAMPUS 
1 2017-06-09 19:53:56.387058-07:00 75 36.979664 -122.058900 OUT OF SERVICE/SORRY 
2 2017-06-09 19:28:53.525189-07:00 75 36.988640 -122.066820 UPPER CAMPUS 
3 2017-06-09 19:30:31.633478-07:00 75 36.991657 -122.066605 UPPER CAMPUS 

我可以得到使用df.groupby(df.time.dt.hour).count()产生这些值:

time id lat lon type 
time      
0 2121 2121 2121 2121 2121 
1 2334 2334 2334 2334 2334 
2 1523 1523 1523 1523 1523 
6 8148 8148 8148 8148 8148 

哪个是正确的:0,1,2是一天的小时。但是,我想表示没有行3,4,5小时的行。对于每个列名都是不必要的,因为每个列的值都是相同的。

回答

1

您可以使用reindex

#if want all hours 
df1 = df.groupby(df.time.dt.hour)[''].count().reindex(range(23), fill_value=0) 

#if want 0 to max hour 
df1 = df.groupby(df.time.dt.hour).count() 
     .reindex(range(df.time.dt.hour.max() + 1), fill_value=0) 
+0

感谢。我没有在我的问题中提到它,但我实际上想要使用fill_value = 0参数来重新索引而不是获取NaN。但这个答案是正确的。 –