How can you pass a function into pd.groupby and call it from there? I have a series with time index and values. Let's say I want to group it by month and call the sum function. But it could be any other (size, average etc.). I want to pass this into the function.
import pandas as pd
#MONTH1 ... #M2
series = pd.Series([1, 2, 2, 2, 5]) # assume time-index on daily observations on Month 1 and Month 2
def custom_calc(series:pd.Series, freq, func):
grouper = series.groupby(pd.Grouper(freq)).func()
return grouper
Output >>
custom_calc(series, "M", sum)
# It combines month 1 observations into a single sum, and month 2 leaves it as it is only 1 observation.
pd.Series([1+2+2+2, 5])