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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With