how to replace multiple values with one value python

后端 未结 4 1666
臣服心动
臣服心动 2021-01-02 09:11

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

         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 10:11

    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.

提交回复
热议问题