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

Change pandas dataframe column value depending on other columns values having three options

I have a Pandas dataframe with a column named col1, and I want to add a new column to the dataframe, which value depends on the content of col1 for each record. I tried this:

d['new_column'] = 'CASE 1' if d['COL1'] == None else 'CASE 2' if d['COL1'] == 0 else 'CASE 3'

But I got this error:

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

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can I make the evaluation to set the values of the new column properly?

>Solution :

Try using np.where. It’s efficient and easy to use for this cases:

import numpy as np

df['new_column'] = np.where(d['COL1'].isnull(), 'CASE1',
                            np.where(d['COL1']==0,'CASE 2','CASE 3')
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