我有一个 Pandas 数据框,其中包含名为 time 的日期时间列。我想计算每小时的行数。问题是我想要结果表处理不存在行的时间。示例:
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 小时没有行。不需要每个列名称,因为每个列的值都是相同的。
最佳答案
您可以使用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)
关于python - 将缺失数据添加到按日期分组的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47863934/