Search code examples
pythonpandasdataframecountaverage

Calculate average by grouping using pandas df


I would like to get average of amount by date i.e., for eg:- my dataframe is like

It should take unique count of months as denominator and sum of all data in the amounts as numerator

Date        amount
2021-12-13  234.89
2021-12-06  456.9
2021-11-26  453.56
2021-11-19  453
2021-11-12  222.4
2021-10-29  123.4
2021-10-22  433.99
2021-10-15  784.99
2021-10-06  678.99

average should be sum of all amount values/count of months using pandas dataframe grouping. in the above example average=sum of amount/3.


Solution

  • After your edit, IIUC:

    df["Month"] = pd.to_datetime(df["Date"]).dt.month
    num_of_months = df["Month"].nunique()
    
    df['avg_per_month'] = sum(df['amount'])/num_of_months