Home > Software design >  python set value of column based on other column value
python set value of column based on other column value

Time:03-16

I have a df

Side ref_price price price_diff
0    100        110
1    110        100

I want to keep price_diff values based on side values.

if side==0:
   df['price_diff']=df['ref_price']*df['price']
else if side==1:
   df['price_diff']=df['ref_price']*df['price']*-1

Tried with

df.loc[df.Side == 0, 'price_diff'] = (df['price']*df['ref_price'])

Not working, throwing errors.

CodePudding user response:

You could use "Side" column as a condition in numpy.where:

df['price_diff'] = np.where(df['Side'].astype(bool), df['ref_price']*df['price']*-1, df['ref_price']*df['price'])

or in this specific case, use "Side" column values as power of -1:

df['price_diff'] = df['ref_price']*df['price']*(-1)**df['Side']

Output:

   Side  ref_price  price  price_diff
0     0        100    110       11000
1     1        110    100      -11000

CodePudding user response:

You can use np.where:

df['price_diff'] = np.where(df['side'] == 0,
                            df['ref_price'] * df['price'],
                            df['ref_price'] * df['price'] * -1)
print(df)

# Output
   side  ref_price  price  price_diff
0     0        100    110       11000
1     1        110    100      -11000
  • Related