Apply ewm function on Pandas groupby

Viewed 503

I have this DataFrame

ddd = pd.DataFrame({'day':['m','t','m','t','m','t','m','t'] 
                    ,'val':[15,2,10,4,5,8,2,10]})

I want to groupby by day and aggregate the val with ewm

If I do groupby and mean I get this

ddd.groupby(['day']).mean()

     val
day     
m      8
t      6

Now same like this if I try

ddd.groupby(['day']).ewm(com=1.0).mean()

I get error AttributeError: 'DataFrameGroupBy' object has no attribute 'ewm'

My expected output would look like this

     val
day     
m      4.733333
t      8.133333
1 Answers

Not all dataframe or series functions are implemented for groupby objects. But you can use apply to get your expected result

ddd.groupby(['day']).apply(lambda x: x.ewm(com=1.0).mean().iloc[-1])

Out:

          val
day          
m    4.733333
t    8.133333
Related