In my code with numpy.select below, I want to put the ELSE in condition section so that it will take care of all remaining scenario. How can I do it?
(The lambda is good to go)
df = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9],
'In': [111, 100, 31, 1100, 12, 33, 21, 32, 33],
'Out': [24, 52, 34, 95, 98, 54, 32, 20, 16]})
conditions = [
df['In'] >100,
df['Out'] > 50,
(df['In']<df['Out']) & (df['Out']>20)
]
choices = [1, 2, 3]
df['check'] = np.select(conditions, choices, default=np.nan)
print(df)
# LAMBDA is good --------------------------------------------------------
df['lamda check'] = df[['In','Out']].apply(lambda x:
1 if x['In']>100 else
2 if x['Out']>50 else
3 if x['In']<x['Out'] and x['Out']>20 else
999, axis=1
)
print(df)
CodePudding user response:
If you want else 999
, then set that as the default
in np.select
:
default
: scalar
The element inserted in output when all conditions evaluate toFalse
.
df['check'] = np.select(conditions, choices, default=999)