1# Method 1:
2df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
3#or
4df.loc[df['set_of_numbers'] <= 4, 'equal_or_lower_than_4?'] = 'True'
5
6# Method 2:
7df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
8#or
9df['name_match'] = df['First_name'].apply(lambda x: 'Match' if x == 'Bill' else 'Mismatch')
10
11# or
12df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match'
13df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch'
14
15
16
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