0

I need to replace my column depending upon data from another dataframe. Have to search for respective "name" from the other dataframe and include the "change_name" in the df1

df1:

ID name 1 cat 2 jack 3 snake 4 monkey 

df2:

name change_name cat meow jack oooo snake ssss monkey 

output:

ID name 1 cat meow 2 jack oooo 3 snake ssss 4 monkey nan 

Sorry, I had to edit my question.

I had to do like below:

def map_name(name): elif name == 'cat': return 'meow' elif name == 'jack': return 'oooo' elif name == 'snake': return 'ssss' elif name == 'monkey ': return None else return name 

df1['name'] = df1['name'].apply(map_name)

As the list is small, I have hardcoded here but the list might grow. Can someone tell how to do teh same functionality using dataframes?

1
  • Use merge with dropna, i.e. df.merge(df2.dropna(),on="name"). Commented Feb 19, 2020 at 6:36

1 Answer 1

2

I think you need:

d = {k:v for k,v in zip(df1["name"], df1["change_name"])} df["new_name"] = df["name"].map(d) df.dropna(subset=["new_name"], inplace=True) print(df) 

output:

 ID name new_name 0 1 cat meow 1 2 jack oooo 2 3 snake ssss 
Sign up to request clarification or add additional context in comments.

1 Comment

dict comprehension is not necessary, check dupe.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.