pythonpandasgroup-bypandas-groupbyforecast

Calculate WMAPE for groupby object with Pandas in Python


I have a dataframe called "revenue" that looks like this:

enter image description here

I want to calculate WMAPE for each month.

https://en.wikipedia.org/wiki/WMAPE

Wikipedia suggests that WMAPE is one scalar number, and I'm struggling to figure out how to calculate that for a groupby object. I know that I have to start by doing this:

revenue.groupby('month')

To calculate WMAPE without group by month, here is my code:

sum(abs(revenue['actual'] - revenue['forecast'])) / sum(abs(revenue['actual']))
Out[1]: 0.12206572769953052

How do I do this for the groupby object?


Solution

  • You can pass your calculation code to groupby.apply:

    revenue.groupby('month').apply(lambda x:sum(abs(x['actual'] - x['forecast'])) / sum(abs(x['actual'])))
    # month
    # July    0.109890
    # June    0.131148
    # dtype: float64