我刚刚在 Pandas 中沾湿了脚趾,然后被卡住了。我想按小时在 CSV 中聚合事件(获取计数),并在事件中指定开始时间和结束时间。
即一个例子是:
event, start, end
soccer, 2020-01-20 00:34:00, 2020-01-20 02:34:00,
football, 2020-01-20 00:34:00, 2020-01-20 01:34:00
etc
预期输出:
00:00:00 - 2 (both began in 0th hour and went to 1st hour)
01:00:00 - 2 (both were live in 1st hour)
02:00:00 - 1 (only soccer occurred in 02 hour)
你会怎么做呢?我一直在尝试重新索引、重新采样、时间差、时间索引——但都没有成功。
最佳答案
您想要的实际上是事件发生时间的频率分布。首先,您需要通过创建一个范围然后分解它来生成要从中获取分布的样本:
hours = events.apply(lambda row: range(row['end'].hour - row['start'].hour + 1), axis=1).explode()
0 0
0 1
0 2
1 0
1 1
dtype: object
不要忘记在结束和开始之间的差值上加一以说明 fencepost error 。
然后只需获取样本的值计数即可。要获取按小时顺序而不是按降序计数的频率,请传递 sort=False
。
hours.value_counts(sort=False)
0 2
1 2
2 1
dtype: int64
关于python - 使用 Python/Pandas 按 csv 中的开始时间和结束时间日期时间列按小时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141865/