【问题标题】:How to replace a substring with another string in a column in pandas [closed]如何用熊猫列中的另一个字符串替换子字符串[关闭]
【发布时间】:2020-01-27 02:44:35
【问题描述】:

我有一栏如下:

df['name']
1                              react trainer
2                              react trainers
3                              react trainer's

我需要将字符串 trainers/trainer 替换为 trainer:

1                              react trainer
2                              react trainer
3                              react trainer

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    df['name'].str.replace('trainer(\'?s)*', 'trainer')
    

    【讨论】:

      【解决方案2】:
      df['name'].str.replace(to_replace ='trainer.*', value = 'trainer', regex = True)
      

      【讨论】:

        【解决方案3】:

        如果您想查找包含此子字符串的行并返回子字符串本身,则应使用正则表达式。我在下面有这个

        import re
        
        def return_substr(string,substring)
          #Check substring
          if re.search(substring,string):
             return(substring)
          #If not found, return ‘’
          else:
             return(‘’)
        
        #Use apply to run this row by row
        df[‘replaceCol’] = df[‘Name’].apply(lambda x: return_substr(x,’react trainer’), axis=1)
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-01
          • 2023-03-19
          • 2019-11-23
          • 2018-09-24
          • 2017-03-12
          • 2011-04-06
          • 2020-03-07
          • 1970-01-01
          相关资源
          最近更新 更多