The Python Oracle

Pandas groupby ewm

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities

--

Chapters
00:00 Pandas Groupby Ewm
02:10 Accepted Answer Score 8
02:26 Answer 2 Score 1
02:45 Answer 3 Score 0
03:03 Thank you

--

Full question
https://stackoverflow.com/questions/5800...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #timeseries #pandasgroupby #rollingcomputation

#avk47



ACCEPTED ANSWER

Score 8


Let's fix the problem, using transform:

t['ewm'] = ts.groupby(['C1'])['X1'].transform(lambda x: x.ewm(halflife=10).mean()).values()



ANSWER 2

Score 1


The accepted answer is very slow for large datasets.

What I have done is:

ts['ewm'] = ts.groupby(['C1']).ewm(halflife=10).mean().values

and it seems to work just fine




ANSWER 3

Score 0


Can you try this? Do NOT set ts = df.set_index('T'). Then you can do as below

ts['ewm']=ts.groupby(['C1'], sort=False).apply(lambda x: x['X1'].ewm(halflife=10).mean()).reset_index(drop=True)