【问题标题】:Group by hour with start time and end time datetime columns in csv with Python/Pandas使用 Python/Pandas 以 csv 中的开始时间和结束时间日期时间列按小时分组
【发布时间】:2020-05-25 06:25:19
【问题描述】:

我只是在 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)

你会怎么做呢?我一直在尝试重新索引、重新采样、时差、时间索引——都没有运气。

【问题讨论】:

    标签: python python-3.x pandas pandas-groupby


    【解决方案1】:

    您想要的实际上是事件发生时间的频率分布。首先,您需要通过创建一个范围然后分解它来生成从中获取分布的样本:

    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
    

    别忘了在 end 和 start 之间的差值上加一以说明fencepost error。 然后只需获取样本的值计数。要按小时而不是按降序获取频率,请传递 sort=False

    hours.value_counts(sort=False)
    
    0    2
    1    2
    2    1
    dtype: int64
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      相关资源
      最近更新 更多