Fabian von Allmen
Fabian von Allmen

Reputation: 43

Find words and create new value in different column pandas dataframe with regex

suppose I have a dataframe which contains:

df = pd.DataFrame({'Name':['John', 'Alice', 'Peter', 'Sue'],
                   'Job': ['Dentist', 'Blogger', 'Cook', 'Cook'], 
                  'Sector': ['Health', 'Entertainment', '', '']})

and I want to find all 'cooks', whether in capital letters or not and assign them to the column 'Sector' with a value called 'gastronomy', how do I do that? And without overwriting the other entries in the column 'Sector'? Thanks!

Upvotes: 0

Views: 42

Answers (2)

Erfan
Erfan

Reputation: 42916

Using Series.str.match with regex and a regex flag for not case sensitive (?i):

df.loc[df['Job'].str.match('(?i)cook'), 'Sector'] = 'gastronomy'

Output


    Name      Job         Sector
0  John   Dentist  Health       
1  Alice  Blogger  Entertainment
2  Peter  Cook     gastronomy   
3  Sue    Cook     gastronomy 

Upvotes: 2

yatu
yatu

Reputation: 88276

Here's one approach:

df.loc[df.Job.str.lower().eq('cook'), 'Sector'] = 'gastronomy'

print(df)

    Name      Job         Sector
0   John  Dentist         Health
1  Alice  Blogger  Entertainment
2  Peter     Cook     gastronomy
3    Sue     Cook     gastronomy

Upvotes: 4

Related Questions