简体   繁体   中英

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!

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM