Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python set value of column based on other column value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Not working, throwing errors.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading