function is not persisting the the replacements

Viewed 18

I have a dataframe and I want to replace a string by another string. I am using this code:

df['text']=df['text'].map(lambda x: x.replace('%%user_article%%','a'))
df['text']=df['text'].map(lambda x: x.replace('%%company_name%%','COMPANY'))

and it's working just fine.

Now I want to define a function with the code above and I did:

  def r_tag(df):
            df=df.map(lambda x: x.replace('%%user_article%%','a') \
            .replace('%%company_name%%','COMPANY'))
            return df

and then r_tag(df['text']

The function above works but don't persist the replacements. How can I fix this?

1 Answers

Problem might be you didn't assign the result back, you can do df['text'] = r_tag(df['text']).

You can also use Series.replace with dictionary and regex=True

d ={'%%article%%':'a', '%%company_name%%': 'COMPANY'}

df['out'] = df['text'].replace(d, regex=True)
print(df)

                                      text              out
0                   I have %%article%% car     I have a car
1                     %%article%%fter dawn       after dawn
2  D%%article%%t%%article%%Fr%%article%%me        DataFrame
3                 this is %%company_name%%  this is COMPANY
Related