Home > Software design >  Return another column's value based on an IF condition [duplicate]
Return another column's value based on an IF condition [duplicate]

Time:10-08

I'm trying to create the total column in Pandas. How it is calculated is as follows - If nb_months = 1 then take the trans_amt as the value if not set to 0.

Trans_amt Nb_months Total
12 1 12
0 5 0
0 7 0
24 9 0

df['Total'] = [df['Trans_amt '] if x == 1 else 0 for x in df['nb_months']]

My code above returns the entire trans_amt series in the total column. Any help would be great.

CodePudding user response:

df['Total'] = np.where(df['nb_months'] == 1,df['Trans_amt'] , 0)

syntax:

np.where(condition, True, False)

  • Related