jeudi 14 janvier 2021

How to apply a function to a dataframe row based on a condition and values of another row?

If I have a pandas dataframe such as:

a   b   c  
1   2   3 
1   2  -3
2   3   2
4   2  -1

How do change the values of column b based on if the values in c are positive or negative, and use the values in b and a in the operation.

I want to run something like this on each row:

   if (c >= 0):
     b = a - b
   else:
     b = b - a 

and get the dataframe:

a   b   c  
1  -1   3 
1   1  -3
2  -1   2
4  -2  -1

Aucun commentaire:

Enregistrer un commentaire