简体   繁体   English

通过pd.Grouper在月初对熊猫进行分组

[英]Pandas grouping by start of the month with pd.Grouper

I have a DataFrame with hourly timestamps: 我有一个带有每小时时间戳记的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

I am using the Pandas Grouper to group and sum the data monthly: 我正在使用Pandas Grouper每月对数据进行分组和汇总:

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

Expected output: 预期产量:

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

Actual output: 实际输出:

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

How can I get the labels of the groups to be the first element in the group? 如何使组的标签成为组中的第一个元素?

Thank you 谢谢

Use the freq MS (Month Start), rather than M (Month End). 使用频率MS(月开始),而不是M(月结束)。

See dateoffset objects in the docs . 请参阅docs中的dateoffset对象

Use resample to aggregate on DatetimeIndex : 使用resample汇总DatetimeIndex

df.resample('MS').sum()

            value
date             
2019-01-01      6
2019-02-01      1
2019-03-01      3
2019-04-01      2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM