1# For creating new column with multiple conditions
2conditions = [
3 (df['Base Column 1'] == 'A') & (df['Base Column 2'] == 'B'),
4 (df['Base Column 3'] == 'C')]
5choices = ['Conditional Value 1', 'Conditional Value 2']
6df['New Column'] = np.select(conditions, choices, default='Conditional Value 1')
1# If you only have one condition use numpy.where()
2# Example usage with np.where:
3df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
4print(df)
5 Type Set
60 A Z
71 B Z
82 B X
93 C Y
10
11# Add new column based on single condition:
12df['color'] = np.where(df['Set']=='Z', 'green', 'red')
13print(df)
14 Type Set color
150 A Z green
161 B Z green
172 B X red
183 C Y red
19
20
21# If you have multiple conditions use numpy.select()
22# Example usage with np.select:
23df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
24print(df)
25 Type Set
260 A Z
271 B Z
282 B X
293 C Y
30
31# Set the conditions for determining values in new column:
32conditions = [
33 (df['Set'] == 'Z') & (df['Type'] == 'A'),
34 (df['Set'] == 'Z') & (df['Type'] == 'B'),
35 (df['Type'] == 'B')]
36
37# Set the new column values in order of the conditions they should
38# correspond to:
39choices = ['yellow', 'blue', 'purple']
40
41# Add new column based on conditions and choices:
42df['color'] = np.select(conditions, choices, default='black')
43
44print(df)
45# Returns:
46 Set Type color
470 Z A yellow
481 Z B blue
492 X B purple
503 Y C black
1# create a list of our conditions
2conditions = [
3 (df['likes_count'] <= 2),
4 (df['likes_count'] > 2) & (df['likes_count'] <= 9),
5 (df['likes_count'] > 9) & (df['likes_count'] <= 15),
6 (df['likes_count'] > 15)
7 ]
8
9# create a list of the values we want to assign for each condition
10values = ['tier_4', 'tier_3', 'tier_2', 'tier_1']
11
12# create a new column and use np.select to assign values to it using our lists as arguments
13df['tier'] = np.select(conditions, values)
14
15# display updated DataFrame
16df.head()