Maybe pandas.DataFrame.rolling is not the best way to do this, please tell me if there is a better approach.
What I want is to have rolling window on df and have all columns from df available in the window to do various calculations.
I believe the code below is very close to my goals, but I struggle understanding the index issue as stated in the code.
At first x.index = RangeIndex(start=0, stop=2, step=1), and tmp_df correctly selects the first and second row in df (index 0 and 1). For the last x.index = RangeIndex(start=4, stop=6, step=1) it seems like iloc tries to select index 6 in df which is out of range (df has index 0 to 5).
What am I missing?
Thank you in advance for any advice.
import numpy as np
import pandas as pd
df = pd.DataFrame({'open': [7, 5, 10, 11,6,12],
'close': [6, 6, 11, 10,7,10],
'positive': [0, 1, 1, 0,1,0]},
)
def do_calculations_on_any_df_column_in_window(x,df):
print("index:",x.index)
tmp_df = df.iloc[x.index] # raises "ValueError: cannot set using a slice indexer with a different length than the value" when x.index = RangeIndex(start=4, stop=6, step=1) as df index goes from 0 to 5 only
# do calulations on any column in tmp_df, get result
result = 1 #dummyresult
return result
intervals = range(2, 10)
for i in intervals:
df['result_' + str(i)] = np.nan
res = df.rolling(i).apply(do_calculations_on_any_df_column_in_window, args=(df,), raw=False)
df['result_' + str(i)][1:] = res
print(df)