Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace_all() r equivalent in python

I am transitioning from R to Python and have a sample dataframe as follows:

df = df = pd.DataFrame({'characterisitics': pd.Series(['Walter White made meth', 'Jessie Pinkman was called meth-head', 'Saul Goodman is always happy']), 'name': pd.Series(['Walter White', 'Jessie Pinkman', 'Saul Goodman'])})

         characteristics                        name
0               Walter White made meth      Walter White
1  Jessie Pinkman was called meth-head     Jessie Pinkman
2         Saul Goodman is always happy       Saul Goodman

I would like to use replace parts of 'characteristics' that match 'name' column for each row. In R, I could have used:

str_replace_all(string = df$characteristics, pattern = fixed(df$name), replacement = '')

And my output would be as follows:

       characteristics            name
0             made meth    Walter White
1  was called meth-head  Jessie Pinkman
2       is always happy    Saul Goodman

What syntax do I use if I want to achieve this in Python?

Thanks!

like image 897
Craig Bing Avatar asked Jul 18 '26 22:07

Craig Bing


1 Answers

I think for this one you have to apply a quick lambda to each row. You don't actually need regex for your simple example so the standard str.replace() works fine:

df.apply(lambda row: row['characterisitics'].replace(row['name'], ''), axis='columns')
Out[8]: 
0                made meth
1     was called meth-head
2          is always happy
dtype: object
like image 85
Marius Avatar answered Jul 20 '26 11:07

Marius