Skip to content
Advertisement

pandas string replace multiple character in a cell

df = pd.DataFrame({'a': ['123']})
     a
0  123

I want to replace 1 with 4, 2 with 5, and 3 with 6

So this is the desired output

     a
0  456

How can I achieve this using pd.str.replace() ?

Advertisement

Answer

Try .replace (not .str.replace) with option regex=True:

df['a'] = df['a'].replace({'1':'4', '2':'5', '3':'6'}, regex=True)

Output:

     a
0  456
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement