Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip rows while looping over dataframe Pandas

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'.

Issue 1 I have is that, when I write 'index = index + 126', for some reason python does not understand that it needs to skip the 126 rows.`

Issue 2 is that, when I add a condition to avoid to have the action column longer than the reversal column, that condition does not work (see code comments).

#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
like image 207
gianluca Avatar asked Oct 14 '25 03:10

gianluca


1 Answers

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
like image 116
Nihal Avatar answered Oct 16 '25 16:10

Nihal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!