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:
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')