0

Hi I have a list and a pandas dataframe

[ apple, tomato, mango ] 
values 

tomato
pineapple
apple
banana
mango 

I would like to replace the column values that appear in the list with the values in the new list as follow

[ fruit1, fruit2, fruit3 ] 

My expected output is a pandas dataframe that looks like this

values 

fruit2
pineapple
fruit1
banana
fruit3

How can I accomplish this efficiently?

2 Answers 2

3

Create a dict and use the map function of a dataframe:

l1 = ["apple", "tomato", "mango"]
l2 = ["fruit1", "fruit2", "fruit3"]

df['values'].map(dict(zip(l1, l2))).fillna(df['values'])

fillna is needed because map by default will convert values that doesn't exists in dict to NaN.

Sign up to request clarification or add additional context in comments.

Comments

0

Create a dictionary with the zip() function and then replace the values:

current = ['apple', 'tomato', 'mango']
to_replace = ['fruit1', 'fruit2', 'fruit3']

replace_dict = dict(zip(current, to_replace))

df.replace(replace_dict, inplace=True)

print(df)
      values
0     fruit2
1  pineapple
2     fruit1
3     banana
4     fruit3

The replace function replaces dataframe values. Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.