Home > OS >  replace column values with values in another list when values appear in a specific list
replace column values with values in another list when values appear in a specific list

Time:12-31

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?

CodePudding user response:

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.

CodePudding user response:

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!

  • Related