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

Convert values to negative on presence of string in another column

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:

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

    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

>Solution :

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
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