简体   繁体   中英

Replace Whole String if it contains substring in pandas dataframe, but with a list of values

Is there a way to do what is done is the below question, but instead of using a single string value, use a dict/array to replace many values in less lines of code?

Replace whole string if it contains substring in pandas

What I have so far:

key = [
    {
        "substr": ["foo1", "foo2"],
        "new_val": "bar"
    },
]

for i in range(len(key)):
    df.loc[df[column].str.contains('|'.join(key[i]['substr'])), column] = key[i]['new_val']

can it be improved?

Try:

for el in key:
    df[column]=df[column].str.replace('.*('+ '|'.join(el["substr"]) +').*', el["new_val"], regex=True)

Outputs (dummy data):

import pandas as pd

key = [
    {
        "substr": ["foo1", "foo2"],
        "new_val": "bar"
    }
]

df=pd.DataFrame({"x": ["foo1xyz", "abcfoo", "zyc", "foyo2foo2g"], "y": [1,2,3,4]})

for el in key:
    df["x"]=df["x"].str.replace('.*('+ '|'.join(el["substr"]) +').*', el["new_val"], regex=True)

>> df

        x  y
0     bar  1
1  abcfoo  2
2     zyc  3
3     bar  4

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