I am struggling with the following and do not seem to find any solution online.
I have a for loop over a dataframe. This loop is supposed to do the following: if the content of column 'reversal' == 1, populate 'action' column with 1, skip 125 rows, populate the next 126th row of 'action' with -1, and continue repeating the loop from the next row. If column 'reversal'!=1, continue with the loop without populating 'action'.
#creating the on/off signal column
df_zinc['action'] = 0
#creating the loop
for index,row in df_zinc.iterrows():
if row.reversal == 1:
df_zinc.loc[index,'action'] = 1
if index<len(df_zinc.index)-126: #the purpose of this condition is to not have the action column longer than the reversal column. Thuogh, it appears not to be working
df_zinc.loc[index+126, 'action'] = -1
index= index + 127
don't use itterrows() if you can use indexing.
try this:
#creating the on/off signal column
# df_zinc['action'] = 0
#
count = 0
# #creating the loop
for index in df_zinc.index:
if index < count:
continue
if df_zinc.at[index , 'reversal'] == 1:
df_zinc.at[index , 'action'] = 1
if index < len(df_zinc)-126: #the purpose of this condition is to not have the action column longer than the reversal column. Thuogh, it appears not to be working
df_zinc.at[index+126, 'action'] = -1
count = index + 127
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With