0

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?

grumpyTofu
  • 826
  • 7
  • 5
  • @PierreV. Sort of. It's definitely a better way of identifying what to replace, but it doesn't help with the replacement of the value depending on what sub-string was found. – grumpyTofu Feb 04 '20 at 17:33

1 Answers1

0

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
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34