np.select with multiple conditions 1

np.select with multiple conditions

conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0

Here is what the above code is Doing:
1. We create a list of conditions, which are Boolean Series.
2. We create a list of choices, which are the values we want to assign when the condition evaluates to True.
3. We use the np.select() function to evaluate each condition and assign the corresponding value from the choices list.
4. We specify a default value of 0 for when none of the conditions evaluate to True.

Similar Posts