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

Question:

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.

Asked By: Asif Sayed

||

Answers:

You can use a simple dict to do that:

d = {k: v for k, v in zip(df['Name'], df['Corrected_Name'])}
f = [d.get(k, k) for k in F]

Reproducible example

df = pd.DataFrame([['a', 'b'], ['b', 'c'], ['foo', 'bar']], columns=['Name', 'Corrected_Name'])
F = ['a', 'aa', 'b', 'hello', 'foo']

# code above

>>> f
['b', 'aa', 'c', 'hello', 'bar']
Answered By: Pierre D

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)
Answered By: CozyCode
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.