Search code examples
pythonpandaswindow-functionsrolling-computation

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?


Solution

  • 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.