简体   繁体   中英

Matching pandas substring with dict key and replacing with dict value

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

Try extract and map:

df['col'].str.extract('({})'.format('|'.join(d.keys())))[0].map(d).dropna()

Output:

0    hello
2    world
Name: 0, dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM