【问题标题】:Pandas grouping by start of the month with pd.Grouper使用 pd.Grouper 按月初分组的熊猫
【发布时间】:2019-10-10 08:31:29
【问题描述】:

我有一个带有每小时时间戳的 DataFrame:

2019-01-01 0:00:00             1
2019-01-01 1:00:00             2
2019-01-11 3:00:00             1
2019-01-21 4:00:00             2
2019-02-01 0:00:00             1
2019-03-05 1:00:00             2
2019-03-21 3:00:00             1
2019-04-08 4:00:00             2

我正在使用 Pandas Grouper 每月对数据进行分组和汇总:

monthly_data = [pd.Grouper(freq='M', label='left')].sum()

预期输出:

2019-01-01 0:00:00             6
2019-02-01 0:00:00             1
2019-03-01 0:00:00             3
2019-04-01 0:00:00             2

实际输出:

2018-12-31 0:00:00             6
2019-01-31 0:00:00             1
2019-02-28 0:00:00             3
2019-03-30 0:00:00             2

如何让组的标签成为组中的第一个元素?

谢谢

【问题讨论】:

    标签: python pandas datetime group-by pandas-groupby


    【解决方案1】:

    使用频率 MS(月开始),而不是 M(月结束)。

    dateoffset objects in the docs

    【讨论】:

      【解决方案2】:

      使用resampleDatetimeIndex 上聚合:

      df.resample('MS').sum()
      
                  value
      date             
      2019-01-01      6
      2019-02-01      1
      2019-03-01      3
      2019-04-01      2
      

      【讨论】:

        猜你喜欢
        • 2020-03-30
        • 2014-12-15
        • 1970-01-01
        • 2016-06-24
        • 2019-08-14
        • 1970-01-01
        • 2019-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多