pandas reversal of numbers based on condition

I have a data frame that looks something like this:

import pandas as pd
d={'name':['edward','margaret'],'sex':['male','female'],'amt':[100,200]}

df=pd.DataFrame(data=d)

I want to reverse the amt column if the sex is 'female'. So I need the amt to be -200 for the second record. Something like:

df.loc[df['sex']=='female','amt']=-200

1 answer

  • answered 2019-05-18 13:55 jezrael

    You are close, only multiple matched rows by -1:

    df.loc[df['sex']=='female','amt'] *= -1
    print (df)
           name     sex  amt
    0    edward    male  100
    1  margaret  female -200
    

    What is simplier version of:

    df.loc[df['sex']=='female','amt'] = df.loc[df['sex']=='female','amt'] * -1