groupby 日期使用除午夜以外的其他开始时间

groupby date using other start time than midnight

我正在按日期汇总一些数据。

for dt,group in df.groupby(df.timestamp.dt.date):
      # do stuff

现在,我想做同样的事情,但不使用午夜作为时间偏移量。 尽管如此,我还是想使用 groupby,但是例如在早上 6 点到早上 6 点的垃圾箱中。 有没有比虚拟列更好的解决方案? 不幸的是,如

中所讨论的那样重新采样

Resample daily pandas timeseries with start at time other than midnight Resample hourly TimeSeries with certain starting hour

不起作用,因为我确实需要应用任何 resampling/aggregation 函数

例如,您可以在分组前减去偏移量:

for dt, group in df.groupby(df.timestamp.sub(pd.to_timedelta('6H')).dt.date):
    # do stuff

resamplepd.Grouper 有一个 base 参数用于处理这种情况。有很多方法可以实现,选择你觉得比较清楚的一个。

  • '1D' 频率 base=0.25
  • '24h' 频率 base=6
  • '1440min'频率与base=360

代码

df = pd.DataFrame({'timestamp': pd.date_range('2010-01-01', freq='10min', periods=200)})

df.resample(on='timestamp', rule='1D', base=0.25).timestamp.agg(['min', 'max'])
#df.resample(on='timestamp', rule='24h', base=6).timestamp.agg(['min', 'max'])
#df.resample(on='timestamp', rule=f'{60*24}min', base=60*6).timestmap.agg(['min', 'max'])

                                    min                 max
timestamp                                                  
2009-12-31 06:00:00 2010-01-01 00:00:00 2010-01-01 05:50:00  #[Dec31 6AM - Jan1 6AM)
2010-01-01 06:00:00 2010-01-01 06:00:00 2010-01-02 05:50:00  #[Jan1 6AM - Jan2 6AM)
2010-01-02 06:00:00 2010-01-02 06:00:00 2010-01-02 09:10:00  #[Jan2 6AM - Jan3 6AM)

为了完整起见,resample 是一种方便的方法,在所有方面都与 groupby 相同。如果出于某种原因你绝对不能使用 resample 你可以这样做:

for dt, gp in df.groupby(pd.Grouper(key='timestamp', freq='24h', base=6)):
    ...

相当于

for dt, gp in df.resample(on='timestamp', rule='24h', base=6):
    ...