【问题标题】:Replacing more than one substring value with pandas str.replace用 pandas str.replace 替换多个子字符串值
【发布时间】:2020-01-09 05:19:33
【问题描述】:

我正在寻找一种方法来简化我的代码:

# Dataset
categorical_data = pd.Series(["dog", "lion", "cat", "crustacean", "dog", "insect", "insect", "cat", "crustacean"])

我想做的是用“动物”代替狗、狮子和猫。我可以这样写:

categorical_data = categorical_data.str.replace("dog", "animal")
categorical_data = categorical_data.str.replace("cat", "animal")
categorical_data = categorical_data.str.replace("lion", "animal")

str.replace() 函数有没有办法接受一个字符串列表而不是一个字符串?

例子:

categorical_data = categorical_data.str.replace([dog, lion, cat], "animal")

【问题讨论】:

    标签: python python-3.x pandas list


    【解决方案1】:

    您可以改为使用带有str.replace 的正则表达式,将字符串分隔为与| 匹配,这将替换指定字符串中的任何 匹配项:

    categorical_data.str.replace(r'(dog|cat|lion)', 'animal', regex=True)
    
    0        animal
    1        animal
    2        animal
    3    crustacean
    4        animal
    5        insect
    6        insect
    7        animal
    8    crustacean
    dtype: object
    

    【讨论】:

      【解决方案2】:

      对于列表替换可以使用Series.replace:

      categorical_data = categorical_data.replace(['dog', 'lion', 'cat'], "animal")    
      print (categorical_data)
      0        animal
      1        animal
      2        animal
      3    crustacean
      4        animal
      5        insect
      6        insect
      7        animal
      8    crustacean
      dtype: object
      

      答案之间的区别在于子字符串替换:

      categorical_data = pd.Series(["dog gorilla", "lion", "cat", "crustacean"])
      
      print (categorical_data.replace(['dog', 'lion', 'cat'], "animal"))
      0    dog gorilla
      1         animal
      2         animal
      3     crustacean
      dtype: object
      
      print (categorical_data.str.replace(r'(dog|cat|lion)', 'animal', regex=True))
      0    animal gorilla
      1            animal
      2            animal
      3        crustacean
      dtype: object
      

      【讨论】:

        猜你喜欢
        • 2019-05-29
        • 2018-08-30
        • 2017-12-06
        • 2016-04-26
        • 2014-12-23
        • 2018-03-26
        • 2022-01-03
        • 2016-11-28
        相关资源
        最近更新 更多