Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas check multiple columns for condition and subtract 1

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading