Python: Match string and replace in place

Viewed 90

I have two dataframes (DF1 & DF2) with multiple columns of text information. I need to match and update one column in DF1

DF1:
Code Name
A    A: Andrew
B    B: Bill
C    C: Chuck
DF2:
Number Codes
1      A
2      B;C
3      A;C

My required output is to transform DF2 as follows:

DF2:
Number Codes
1      A: Andrew
2      B: Bill;C: Chuck
3      A: Andrew;C: Chuck

So far I have tried to use:

df2['Codes'] = df2['Codes'].replace(to_replace="A", value="A: Andrew", regex=True)

But this is not practical for larger datasets.

Do I use the same df.replace function and do some looping to find every code and replace? Or is there other ways to do it better?

One option I'm trying to learn about is using sub() with regex, but i'm new to regex and learning the basics of it.

1 Answers

You should just try to split Column then apply dict with zip and replace

di=dict(zip(df1.Name.str.split(":").str[0],df1.Name))

df2["Codes"]=df2["Codes"].replace(di, regex=True)
Related