【问题标题】:Group time series by a custom fixed period按自定义固定时间段对时间序列进行分组
【发布时间】:2016-02-11 21:59:52
【问题描述】:

我想按固定时间段对时间序列进行分组,其行为与函数 to_period() 完全相同,但具有自定义时间段。

# Some test data
df = pd.DataFrame({'categ': np.random.choice([1,2,3], 12)}, index=pd.date_range(start=pd.to_datetime('2015-01-01'),periods=12, freq='M'))

print(df.groupby(df.index.to_period('M')).sum().head(2))

         categ
2015-01      1
2015-02      3

但我想按自定义时间段对时间序列进行分组,例如 2 个月(双月一次)。不幸的是,to_period('2M') 不起作用,如果我使用TimeGrouper,则期间不固定,它们与开始日期相关。

print(df.groupby(pd.TimeGrouper('2M')).sum().head(2))

            categ
2015-01-31      3
2015-03-31      4

无论数据如何(1 月至 2 月、3 月至 4 月等),预期的行为都是具有相同的固定周期(如一个季度,但为两个月)。 有谁知道解决方案?提前致谢。

           categ
2015-02      3
2015-04      4

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    这是我为满足特定需求而使用的解决方案。如果有人有更好的答案,请告诉我。

    freq = '2M'
    df[freq] = df.index.to_period(freq)
    # Adding a month each even month
    df[freq] = df[freq] + df[freq].dt.month % 2 * MonthEnd()
    print(df.groupby(freq).sum().head(2))
    
             categ
    2M            
    2015-02      5
    2015-04      2
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2015-12-19
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2022-12-05
      • 2016-04-02
      • 2016-10-28
      相关资源
      最近更新 更多