【问题标题】:Pandas - Group into 24-hour blocks, but not midnight-to-midnightPandas - 按 24 小时分组,但不是午夜到午夜
【发布时间】:2016-07-28 23:26:28
【问题描述】:

我有一个时间序列。我想从早上 8 点到第二天早上 7:59 分成 24 小时的块。我知道如何按日期分组,但我尝试使用 TimeGroupers 和 DateOffsets 处理这 8 小时的偏移量,但未能成功。

【问题讨论】:

    标签: pandas time-series dataframe grouping


    【解决方案1】:

    我认为您可以将Grouper 与参数base 一起使用:

    print df
                     date  name
    0 2015-06-13 00:21:25     1
    1 2015-06-14 01:00:25     2
    2 2015-06-14 02:54:48     3
    3 2015-06-15 14:38:15     2
    4 2015-06-15 15:29:28     1
    
    print df.groupby(pd.Grouper(key='date', freq='24h', base=8)).sum()
                         name
    date                     
    2015-06-12 08:00:00   1.0
    2015-06-13 08:00:00   5.0
    2015-06-14 08:00:00   NaN
    2015-06-15 08:00:00   3.0
    

    【讨论】:

      【解决方案2】:

      除了@jezrael 的方法,您还可以使用自定义分组功能:

      start_ts = '2016-01-01 07:59:59'
      df = pd.DataFrame({'Date': pd.date_range(start_ts, freq='10min', periods=1000)})
      
      def my_grouper(df, idx):
          return df.ix[idx, 'Date'].date() if df.ix[idx, 'Date'].hour >= 8 else df.ix[idx, 'Date'].date() - pd.Timedelta('1day')
      
      df.groupby(lambda x: my_grouper(df, x)).size()
      

      测试:

      In [468]: df.head()
      Out[468]:
                       Date
      0 2016-01-01 07:59:59
      1 2016-01-01 08:09:59
      2 2016-01-01 08:19:59
      3 2016-01-01 08:29:59
      4 2016-01-01 08:39:59
      
      In [469]: df.tail()
      Out[469]:
                         Date
      995 2016-01-08 05:49:59
      996 2016-01-08 05:59:59
      997 2016-01-08 06:09:59
      998 2016-01-08 06:19:59
      999 2016-01-08 06:29:59
      
      In [470]: df.groupby(lambda x: my_grouper(df, x)).size()
      Out[470]:
      2015-12-31      1
      2016-01-01    144
      2016-01-02    144
      2016-01-03    144
      2016-01-04    144
      2016-01-05    144
      2016-01-06    144
      2016-01-07    135
      dtype: int64
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-13
        • 2014-04-15
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 2015-09-24
        相关资源
        最近更新 更多