1conditions = [
2 df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
3 df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
4]
5
6choices = [5,5]
7
8df['points'] = np.select(conditions, choices, default=0)
9
10print(df)
11 gender pet1 pet2 points
120 male dog dog 5
131 male cat cat 5
142 male dog cat 0
153 female cat squirrel 5
164 female dog dog 5
175 female squirrel cat 0
186 squirrel dog cat 0
19
1#Using .assign you can make multiple
2#operations that depend on the
3#previous ones without the need
4#of creating intermediate variables
5import pandas as pd
6
7df = pd.DataFrame({
8 'name': ['alice','bob','charlie','daniel'],
9 'age': [25,66,56,78]
10})
11
12df.assign(
13 is_senior = lambda dataframe: dataframe['age'].map(lambda age: True if age >= 65 else False)
14).assign(
15 name_uppercase = lambda dataframe: dataframe['name'].map(lambda name: name.upper()),
16).assign(
17 name_uppercase_double = lambda dataframe: dataframe['name_uppercase'].map(lambda name: name.upper()+"-"+name.upper())
18)
19