Home > Software design >  Pandas check multiple columns for condition and subtract 1
Pandas check multiple columns for condition and subtract 1

Time:12-19

I have created the following Dataframe (Which in reality if 1000 rows and 20 columns):

d = {'col1': [0, 0, 4, 6], 'col2': [3, 4, 0, 0], 'col3': [0, 10, 0, 0], 'END': [0, 0, 0, 0]}
df = pd.DataFrame(data=d)
print(df)

Out:
   col1  col2  col3  END
0     0     3     0    0
1     0     4    10    0
2     4     0     0    0
3     6     0     0    0

I now want to create a loop for every column by index to do the following: Check if the current column is >0 and if yes, if the next column is equal to 0. If both are true, then subtract 1 and move to the next column and repeat.

So far my best try was with a while loop to find the correct fields:

Counter = len(list(df))
i = 0
while 0 < Counter:
    if df.iloc[:,i] > 0 and df.iloc[:,i 1] == 0:
        df.iloc[:,i] - 1
    i = i  1

This code however raises a value error. Can someone help please?

My desired result would look like this:

Out:
   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0

CodePudding user response:

This should be pretty fast:

df[df.ne(0) & df.shift(-1, axis=1).eq(0)] -= 1

Output:

>>> df
   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0

CodePudding user response:

Another option

df.sub(df.shift(-1, axis=1).eq(0)).clip(0)

   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0
  • Related