python - 将缺失数据添加到按日期分组的数据框中

标签 python pandas

我有一个 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/

相关文章:

python - 是否有更优雅/pythonic 的方式来表达这种结构?

python - 使用ReferenceProperty时如何查询数据存储?

python 迭代字符串

python - 数组元素操作

python - delete_message_batch 并没有真正从 SQS 队列中删除消息

python - 强制将 DatetimeIndex 与 Pandas 一起使用

python - 每隔一列除以最后一列中的值

python - 在名称已更改的列中查找唯一值时出现 Pandas 错误

python - Pandas 计算频率周期

python - 列表总和,不改变列表pandas的长度