Messor
Messor

Reputation: 101

Apply custom window function in pandas rolling

I have a DataFrame, e.g.

df = pd.DataFrame([1,2,3,4,5,6,7,8,9])

Now I want to apply a rolling mean, e.g.

df.rolling(window=3, win_type=None).mean()

which gives me a result with evenly weighted elements. Now I want to change the window function. I know, that this is possible by passing a string (e.g. 'hann') to the win_type parameter.

df.rolling(window=3, win_type='hann').mean()

Now the interesting point for me would be to apply a window function, that uses an exponentially decaying weighting, giving a high weight to the value "on the right" and lower weights to values "further to the left". This should be possible by using scipy.signal.windows.exponential and adjusting the parameters. However, I am struggling with passing those parameters as win_type only takes strings.

When I try win_type='exponential' I get ValueError: exponential window requires tau.

Can someone tell me how to pass parameters such as tau to win_type or even create a window function oneself?

Upvotes: 0

Views: 1555

Answers (2)

Stepan
Stepan

Reputation: 629

The answer is here
Important. Solution depends on pandas version.
Python common

import pandas as pd
df = pd.DataFrame([1,2,3,4,5,6,7,8,9])

In the case of tau=10.
For Pandas='0.24.2'

df.rolling(window=(3,10), win_type='exponential').mean()

For Pandas='1.1.3'
df.rolling(window=3, win_type='exponential').mean(tau=10)

Do not hesitate to add other version dependencies.

Upvotes: 2

Messor
Messor

Reputation: 101

Figured it out with an answer from the link provided by Stepan: Tau has to be passed in the function call, i.e.

df.rolling(window=(3), win_type='exponential').mean(tau=10)

Upvotes: 1

Related Questions