Home > OS >  Convert values to negative on presence of string in another column
Convert values to negative on presence of string in another column

Time:07-12

I have a df where I want to convert the value in column a to a negative, if the string in column b is "negative".

consider the following:

df = pd.DataFrame(np.array([[1, "postive"], [1, "negative"]]), columns=['a', 'b'])
print(df)

    a   b
0   1   postive
1   1   negative

I would like to convert the df to look like this:

    a   b
0   1   postive
1   -1  negative

This question is similar to one I found, however I couldn't see how to easily convert the answers of this question to apply for my own problem: Convert values to negative on the condition of values from another column

CodePudding user response:

You can use a mask:

# df['a'] = df['a'].astype(int)

df['a'] = df['a'].mask(df['b'].eq('negative'), -df['a'])

Or, if you are unsure whether the initial number if positive or already negative:

df['a'] = df['a'].mask(df['b'].eq('negative'), -df['a'].abs())

and if there is also a chance that positive values are incorrectly set as negative:

df['a'] = df['a'].abs().mask(df['b'].eq('negative'), -df['a'])

output:

    a         b
0   1   postive
1  -1  negative

CodePudding user response:

You can use numpy.where:

import numpy as np
df['a'] = df['a'].astype(int).mul(np.where(df['b']=='postive', 1, -1))
print(df)

   a         b
0  1   postive
1 -1  negative
  • Related