How to Replace Multiple Values with One Value Python

How can I replace the data 'Beer','Alcohol','Beverage','Drink' with only 'Drink'.

df.replace(['Beer','Alcohol','Beverage','Drink'],'Drink')

doesn't work

2

5 Answers

You almost had it. You need to pass a dictionary to df.replace.

df

       Col1
0      Beer
1   Alcohol
2  Beverage
3     Drink
df.replace(dict.fromkeys(['Beer','Alcohol','Beverage','Drink'], 'Drink'))

    Col1
0  Drink
1  Drink
2  Drink
3  Drink

This works for exact matches and replacements. For partial matches and substring matching, use

df.replace(
    dict.fromkeys(['Beer','Alcohol','Beverage','Drink'], 'Drink'), 
    regex=True
)

This is not an in-place operation so don't forget to assign the result back.

3

Try the following approach:

lst = ['Beer','Alcohol','Beverage','Drink']
pat = r"\b(?:{})\b".format('|'.join(lst))

df = df.replace(pat, 'Drink', regexp=True)
1

Looks like different from MaxU's solution :)

df.replace({'|'.join(['Beer','Alcohol','Beverage','Drink']):'Drink'},regex=True)
1

It seems that your initial method of doing it works in the the latest iteration of Python.

df.replace(['Beer','Alcohol','Beverage','Drink'],'Drink', inplace=True)

Should work

Slight change in earlier answers: Following code Replacing values of specific column/Columns

df[['Col1']] = df[['Col1']].replace(dict.fromkeys(['Beer','Alcohol','Beverage','Drink'], 'Drink'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest