turtle_in_mind
turtle_in_mind

Reputation: 1152

Apply qcut to rolling analysis

I would like to apply pandas qcut to a rolling window. I’m not sure how to go about doing this...idea is to take last 20 days, find the values which fall in the upper quartile, find the averages of values in the upper quartile. And return the average for that one rolled time series.

So if I have

s = pd.Series([5,6,10,12,13,13,20,21,22])
s.rolling(2,2).apply(lambda x: pd.qcut(x,5))

This results in

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
5   NaN
6   NaN
7   NaN
8   NaN
dtype: float64

How do I get the qcut intervals for each time series ? Thanks. Note in the example I have a 2 day rolling window. It’s just to make things simpler

Upvotes: 3

Views: 1341

Answers (1)

Ben.T
Ben.T

Reputation: 29635

I think you can do it by selectioning in your apply the x that correspond to the highest quartile. With a rolling of 6 and q=4, you can do:

print (s.rolling(6,6).apply(lambda x: x[pd.qcut(x, q=4, labels=[1,2,3,4]) == 4].mean()))
0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
5    13.0
6    20.0
7    20.5
8    21.5
dtype: float64

I use the labels parameter to be able to select the higher quartile (here name 4) that will have different value for each rolling so not sure how to do differently.

Upvotes: 3

Related Questions