1df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
2
1import pandas as pd
2
3names = {'First_name': ['Jon','Bill','Maria','Emma']}
4df = pd.DataFrame(names,columns=['First_name'])
5
6df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match'
7df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch'
8
9print (df)
10
1df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
2
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()
1import pandas as pd
2
3numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]}
4df = pd.DataFrame(numbers,columns=['set_of_numbers'])
5
6df['equal_or_lower_than_4?'] = df['set_of_numbers'].apply(lambda x: 'True' if x <= 4 else 'False')
7
8print (df)
9