pandas rolling() function with monthly offset pandas rolling() function with monthly offset pandas pandas

pandas rolling() function with monthly offset


Here is a function that gives you the rolling sum of a specified number of months. You did not provide variable 'dt' in your code above so I just created a list of datetimes (code included).

from datetime import datetimefrom dateutil.relativedelta import relativedeltaimport pandas as pdimport numpy as npimport randomdef date_range(start_date, end_date, increment, period):    result = []    nxt = start_date    delta = relativedelta(**{period:increment})    while nxt <= end_date:        result.append(nxt)        nxt += delta    return resultdef MonthRollSum(df, offset, sumColumn):    #must have DateTimeIndex    df2 = df.copy()    df2.index = df2.index + pd.DateOffset(days = -offset)    return df2.groupby([df2.index.year, df2.index.month])[sumColumn].sum()# added this part to generate the dt list for 8hour interval for 1000 daysstart_date = datetime.now()end_date = start_date + relativedelta(days=1000)end_date = end_date.replace(hour=19, minute=0, second=0, microsecond=0)dt = date_range(start_date, end_date, 8, 'hours')# the following was given by the questionerdft = pd.DataFrame(np.random.randint(0,10,size=len(dt)),index=dt)dft.columns = ['value']dft['value'] = np.where(dft['value'] < 3,np.nan,dft['value'])dft = dft.dropna()# Call the solution functiondft = MonthRollSum(dft, 2, 'value')dft

The results many vary because the initial list of value is randomly generated:

2021  2     290.0      3     379.0      4     414.0      5     368.0      6     325.0      7     405.0      8     425.0      9     380.0      10    393.0      11    370.0      12    419.02022  1     377.0      2     275.0      3     334.0      4     350.0      5     395.0      6     376.0      7     420.0      8     419.0      9     359.0      10    328.0      11    394.0      12    345.02023  1     381.0      2     335.0      3     352.0      4     355.0      5     376.0      6     350.0      7     401.0      8     443.0      9     394.0      10    394.0