简体   繁体   中英

How to replace multiple instances of substrings based on dictionary key value pairs?

Dataframe
|Name|
|----|
|abc |
|pqr |
|xyz |

Input Dict: {a:1,b:2,p:3,r:4}

output
Dataframe
|Name|
|----|
|12c |
|3q4 |
|xyz |
My loop is given below
for k,l in dict:
    for z in df:
        if k in z:
            new_string = z.replace(k,l)

            rows_with_replacement.append(new_string)
        else:
            new_string=z
            rows_with_replacement.append(new_string)

Use Series.str.translate() :

df = pd.DataFrame({'Name': ['abc', 'pqr', 'xyz']})
d = {'a': '1', 'b': '2', 'p': '3', 'r': '4'}
df.Name = df.Name.str.translate(str.maketrans(d))
print(df)

Result:

  Name
0  12c
1  3q4
2  xyz

For multiple symbols:

df = pd.DataFrame({'Name': ['abc', 'pqr', 'xyz']})
d = {'ab': '11', 'b': '2', 'pq': '33', 'r': '4'}

df.Name = df.Name.str.replace('|'.join(d.keys()), lambda x: d[x[0]], regex=True)
print(df)
  Name
0  11c
1  334
2  xyz

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