Creating a Pandas column based on values of other columns [duplicate]
Could use np.select(list of conditions, listof choices, alternative choice)
df['new']=np.select([df['col2']=='we',(df['col2']=='ee')|(df['col3'].isin(['y2','y3']))],['N1','N2'],'N3')
col1 col2 col3 new
0 23 we y1 N1
1 45 ee y2 N2
2 21 cv y3 N2
You need the word or
(and some parantheses):
import pandas as pd
import numpy as np
raw_data = {'col1': [23,45,21],'col2': ['we', 'ee', 'cv'],'col3': ['y1', 'y2', 'y3']}
df = pd.DataFrame(raw_data, columns = ['col1','col2','col3'])
df['newCol'] = [
'N1' if c1 == 'we' else
'N2' if (c1 == 'ee' or np.isin(c2, ['y2', 'y3'])) else
'N3'
for c1, c2 in zip(df['col2'], df['col3'])
]