Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
Pandas check multiple columns for condition and subtract 1

I have created the following Dataframe (which in reality is 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

Now I want to create a loop for every column by index to do the following: check if the current item in the column is greater than 0 and if yes, if the item in the column next to the right is equal to 0. If both are true, then subtract 1 from the item in the column 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.

My desired result would look like this:

   col1  col2  col3  END
0     0     2     0    0
1     0     4     9    0
2     3     0     0    0
3     5     0     0    0
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!