import numpy as np import pandas as pd from datetime import datetime from pandas.tseries.offsets import Day, MonthEnd
sj = pd.Series(np.random.randn(20),
index=pd.date_range('1/15/2022', periods=20, freq='3d'))
sj
2022-01-15 0.852965 2022-01-18 -0.955869 2022-01-21 -0.023493 2022-01-24 -2.304234 2022-01-27 -0.652469 2022-01-30 -1.218302 2022-02-02 -1.332610 2022-02-05 1.074623 2022-02-08 0.723642 2022-02-11 0.690002 2022-02-14 1.001543 2022-02-17 -0.503087 2022-02-20 -0.622274 2022-02-23 -0.921169 2022-02-26 -0.726213 2022-03-01 0.222896 2022-03-04 0.051316 2022-03-07 -1.157719 2022-03-10 0.816707 2022-03-13 0.433610 Freq: 3D, dtype: float64
使用本月末最后一天分组
offset = MonthEnd() sj.groupby(offset.rollforward).mean()
2022-01-31 -0.716900 2022-02-28 -0.068394 2022-03-31 0.073362 dtype: float64
等同于使用重采样
sj.resample('M').mean()



