Python: How to return value in another cell from the same row if condition meet

Here is my code:

def value2(df): if df['condition'] == '-1': return df['value'] else: return 0

Data['value2']=Data.apply(value2, axis=1)

Here is my original table Data:

 id condition value
 1  1         10
 2  0         5
 3  -1        20

Here is the desire output:

 id condition value value2
 1  1         10    0
 2  0         5     0
 3  -1        20    20

Could someone help me fix the code? thank you!

1 answer

  • answered 2020-10-16 04:34 moys

    I think it can be done simply with np.where instead of creating a new function. You can use ge(0) to evaluate values greater than & equal to zero.

    df['value2'] = np.where(df['condition'].ge(0),0,df['value'])