how to column in pandas using the if else code example
Example 1: pandas if else new column
df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
df.loc[df['set_of_numbers'] <= 4, 'equal_or_lower_than_4?'] = 'True'
df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
df['name_match'] = df['First_name'].apply(lambda x: 'Match' if x == 'Bill' else 'Mismatch')
df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match'
df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch'
Example 2: if else python pandas dataframe
conditions = [
(df['likes_count'] <= 2),
(df['likes_count'] > 2) & (df['likes_count'] <= 9),
(df['likes_count'] > 9) & (df['likes_count'] <= 15),
(df['likes_count'] > 15)
]
values = ['tier_4', 'tier_3', 'tier_2', 'tier_1']
df['tier'] = np.select(conditions, values)
df.head()