pythonpandasrolling-computationperiodicity

pandas: rolling with periodic boundaries


Is it possible to include the start and end index values in when using the rolling function in pandas such that the values of the series are periodic?

For example, I have the following Series instance:

import pandas as pd
timestamps = [1, 2, 3, 4]
quantities = [1, 16, 9, 4]
series = pd.Series(quantities, index=timestamps)

which when I type:

series.rolling(window=3, min_periods=3, center=True).median()

yields:

1    NaN
2    9.0
3    9.0
4    NaN
dtype: float64

However, I'd like to include either ends of the series in the calculation such that the result is:

1    median([4, 1, 16])   4.0
2    median([1, 16, 9])   9.0
3    median([16, 9, 4])   9.0
4    median([9, 4, 1])    4.0
dtype: float64

Thanks for any help trying to achieve this!


Solution

  • We can extend the list with the first and last element and then calculate the rolling median. After that we dropna and assign the series back

    Wont win the price for most beautiful code, but it does the job. Could not think of another way.

    quantities2 = quantities.copy()
    quantities2.insert(0, quantities2[-1])
    quantities2.insert(len(quantities2), quantities2[0])
    print(quantities2)
    
    [4, 1, 16, 9, 4, 4]
    
    series = pd.Series(quantities2)
    series = pd.Series(series.rolling(window=3, min_periods=3, center=True).median().dropna(), index=timestamps)
    
    print(series)
    1    4.0
    2    9.0
    3    9.0
    4    4.0
    dtype: float64
    

    But then again, do we have to write cleanest code? :)