if else in pandas code example
Example 1: pandas lambda if else
df['equal_or_lower_than_4?'] = df['set_of_numbers'].apply(lambda x: 'True' if x <= 4 else 'False')
Example 2: make a condition statement on column pandas
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
Example 3: pandas if else
df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
Example 4: if condition dataframe python
df.loc[df['age1'] - df['age2'] > 0, 'diff'] = df['age1'] - df['age2']
Example 5: python conditionally create new column in pandas dataframe
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
conditions = [
(df['Set'] == 'Z') & (df['Type'] == 'A'),
(df['Set'] == 'Z') & (df['Type'] == 'B'),
(df['Type'] == 'B')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)
Set Type color
0 Z A yellow
1 Z B blue
2 X B purple
3 Y C black
Example 6: 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()