Skip to content
Advertisement

Need to find and replace/correct list from another df column

I have a list let suppose F = [Jonii, Max, anna, xyz, etc..] and df which contains 2 column- Name and Corrected_Name. df

I need to search each string from list into df[Name] and replace it with df[Corrected_Name]. For eg. in above, code will search list in df[Name] and if found which is “Jonii” then replace it with “Jon” which is from df[Corrected_Name]. So finally output will be f = [Jon, Max, anna, xyz, etc..]

Thanks in advance!! I am learner so pls ignore writing mistakes.

Advertisement

Answer

Maybe like this (Admittedly this is not the best way to do it):

import pandas as pd

df = pd.DataFrame({"Name": ["Johnii", "Tommi", "Marc"], "CorrectedName": ["John", "Tom", "Mark"]})
names = ["Johnii", "Elizabeth", "Arthur", "Tommi"]

output = []
for name in names:
    updated_value = [cn for n, cn in zip(df['Name'], df['CorrectedName']) if n == name]
    output.append(updated_value[0] if updated_value else name)

print(output)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement