Assume I have df and d below. I want to, for each row in col, check if there is a match with an item key in d, and if so replace the value in col with the corresponding item value, otherwise drop that row. (There can't be more than one match).
df = pd.DataFrame({'col': ['sdffzdhellojkh', 'fegky', 'ouewfzdworldqf']})
d = {'fzdhello': 'hello', 'fzdworld': 'world'}
The output in this case would look like:
df
col
0 hello
1 world
series.str.extract then map:
df['col'].str.extract('('+ '|'.join(d.keys()) + ')',expand=False).map(d).dropna()
0 hello
2 world
Name: col, 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