Adriana van Leeuwen
Adriana van Leeuwen

Reputation: 41

Update dataframe values that match a regex condition and keep remaining values intact

The following is an excerpt from my dataframe:

In[1]: df
Out[1]:
     LongName   BigDog   
1     Big Dog        1  
2     Mastiff        0    
3     Big Dog        1   
4         Cat        0   

I want to use regex to update BigDog values to 1 if LongName is a mastiff. I need other values to stay the same. I tried this, and although it assigns 1 to mastiffs, it nulls all other values instead of keeping them intact.

def BigDog(longname): 
    if re.search('(?i)mastiff', longname):
        return '1'

df['BigDog'] = df['LongName'].apply(BigDog) 

I'm not sure what to do, could anybody please help?

Upvotes: 0

Views: 102

Answers (1)

Erfan
Erfan

Reputation: 42916

You don't need a loop or apply, use str.match with DataFrame.loc:

df.loc[df['LongName'].str.match('(?i)mastiff'), 'BigDog'] = 1

  LongName  BigDog
1  Big Dog       1
2  Mastiff       1
3  Big Dog       1
4      Cat       0

Upvotes: 1

Related Questions