'Rolling Window Size based on Column Value using Groupby, Apply Lambda and iAt

Trying to find the Min and Max values within a look back period which is indicated the BarsLapsed column. This is the statement I am having trouble with:

.apply(lambda x: x.Low.rolling(x.BarsLapsed.iat[x.name], min_periods=0).min())

  • The error is ValueError: iAt based indexing can only have integer indexers

If I use .iat[0] the code works, but the window is fixed and not moving down within the BarsLapsed column values.

import pandas as pd 
import numpy as np
import os

df = pd.read_csv('C:/Data.csv')
df['Date']= pd.to_datetime(df['Date'])
df['BarsLapsed'] = np.where( pd.isna(df['BarsLapsed']), 0, df['BarsLapsed']+1)
df['BarsLapsed'] = df['BarsLapsed'].apply(lambda x: int(x)) 

df = df.sort_values(['Market','Ticker','Date'], ascending=[True,True,True])

df['Rolling_min'] = (df.iloc[::1].groupby('Ticker')
                       .apply(lambda x: x.Low.rolling(x.BarsLapsed.iat[x.name], min_periods=0).min())
                       .reset_index(level=0, drop=True))

print(df)

Picture of Data Layout



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source