pandas 如何用一个值替换多个值python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46920454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:41:30  来源:igfitidea点击:

how to replace multiple values with one value python

pythonstringpandasdataframereplace

提问by Jiayang Zhuo

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

如何'Beer','Alcohol','Beverage','Drink'仅用'Drink'.

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

doesn't work

不起作用

回答by cs95

You almosthad it. You need to pass a dictionary to df.replace.

几乎拥有它。您需要将字典传递给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.

这不是就地操作,所以不要忘记将结果分配回来。

回答by MaxU

Try the following approach:

尝试以下方法:

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

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

回答by YOBEN_S

Looks like different from MaxU's solution :)

看起来与 MaxU 的解决方案不同:)

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

回答by Yashodhan Pawar

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'))