如何在熊猫列中用另一个字符串替换子字符串

时间:2019-09-26 19:07:28

标签: python pandas

我有一列如下:

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

我需要将字符串教练/教练替换为教练:

1                              react trainer
2                              react trainer
3                              react trainer

3 个答案:

答案 0 :(得分:1)

df['name'].str.replace('trainer(\'?s)*', 'trainer')

答案 1 :(得分:0)

df['name'].str.replace(to_replace ='trainer.*', value = 'trainer', regex = True)

答案 2 :(得分:-1)

如果要查找带有此子字符串的行并返回子字符串本身,则应使用正则表达式。我在下面

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)