Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda