abergem
abergem

Reputation: 111

Computing rolling median with a fixed start date in pandas

I have a pandas DataFrame with the following .head():

       EC       Date       PE
0  C00529 2000-01-31  21.8799
1  C00529 2000-02-29  24.4603
2  C00529 2000-03-31  17.2053
3  C00529 2000-04-30  17.5083
4  C00529 2000-05-31  18.0368

EC is an id for the company. I would like to have a column with the median of 'PE' for each company, but rolling from the minimum date ('Date'). Any idea how to do this in pandas?

Thank you!

Upvotes: 0

Views: 52

Answers (1)

Tarifazo
Tarifazo

Reputation: 4343

You can use the df.expanding method (see here). Assuming your DataFrame is sorted:

df.expanding()['PE'].median()

Assuming it is not sorted:

df.loc[df['Date'].sort_values().index].expanding()['PE'].median()

Upvotes: 2

Related Questions