Skip to content Skip to sidebar Skip to footer

Replacing A Pandas Substring With Value From A Column/series

I am trying to replace a Pandas substring with the value from a pandas column. This question has not been answered before. I have tried using the .replace() method but it throws ou

Solution 1:

You need python re.sub and listcomp

import re

df['new_name'] = [re.sub(r'\(\w+\)', r, s) for r, s in zip(df.name2, df.name)]

Out[280]:
   id       name  name2     new_name
0   1  name1 (C)   Jane   name1 Jane
1   2  name2 (B)  Abbie  name2 Abbie
2   3      name3   Luke        name3
3   4      name4  Peter        name4

Post a Comment for "Replacing A Pandas Substring With Value From A Column/series"