How to access individual elements within a rolling window on a dataframe
Using a lambda expression within .apply() will pass an array into the custom function (find_recession_start), and so I can just access the elements as I would any list/array e.g. arr[0], arr[1], arr[2]
df = pd.DataFrame(data=np.random.randint(0,10,10), columns=['GDP'])def my_func(arr): if((arr[2] < arr[1]) & (arr[1] < arr[0])): return 1 else: return 0df['Result'] = df.rolling(window=3).apply(lambda x: my_func(x))df GDP Result0 8 NaN1 0 NaN2 8 0.03 1 0.04 9 0.05 7 0.06 9 0.07 8 0.08 3 1.09 9 0.0
The short answer is: you can't, but you can use your knowledge about the structure of the dataframe/series.
You know the size of the window, you know the current index - therefore, you can output the shift relative to the current index:
Let's pretend, here is your gdp:
In [627]: gdpOut[627]:0 81 02 03 44 05 36 67 28 59 5dtype: int64
The naive approach is just to return the (argmin() - 2)
and add it to the current index:
In [630]: gdp.rolling(window=3).apply(lambda win: win.argmin() - 2) + gdp.indexOut[630]:0 NaN1 NaN2 1.03 1.04 2.05 4.06 4.07 7.08 7.09 7.0dtype: float64
The naive approach won't return the correct result, since you can't predict which index it would return when there are equal values, and when there is a rise in the middle. But you understand the idea.