str.replace 除非字符串后跟某些文本

先前问题的修改:

如何将所有“,”(即逗号然后空格)替换为“_”,除非“,”(逗号然后空格)后跟单词“LLC”或“Inc”(然后什么都不做)?

我想改变:

  1. “德克萨斯能源互助有限责任公司、鲍比·吉利姆、史蒂夫·佩雷拉和安迪·斯蒂特”

  2. “葡萄有限责任公司、安德里亚·格雷、杰克·史密斯”

  3. “史蒂芬·温特斯,苹果,梨公司,莎拉·史密斯”

对此:

  1. “德克萨斯能源互助有限责任公司_BOBBY GILLIAM_STEVE PEREIRA_ANDY STITT”

  2. “葡萄有限责任公司_安德里亚·格雷_杰克·史密斯”

  3. “史蒂芬·温特斯_苹果_梨公司_莎拉·史密斯”

我认为它会从下面代码的一些变化开始,但我无法弄清楚例外条件。

df['Column_Name'] = df['Column_Name'].str.replace(', ','_') 干杯!


撒科打诨
浏览 55回答 3
3回答

四季花海

您可以将正则表达式替换为负lookahead:#no idea why Inc|LLC or LLC|Inc will skip the firstdf['Column_Name'].str.replace(', (?!=|Inc|LLC)', '_')输出:0    TEXAS ENERGY MUTUAL, LLC_BOBBY GILLIAM_STEVE P...1                    Grape, LLC_Andrea Gray_Jack Smith2          Stephen Winters_Apple_pear, Inc_Sarah SmithName: ColumnName, dtype: object

炎炎设计

使用 python 正则表达式模块re for 与模式, (?!Inc|LLC)查找所有出现的 , 不带以下Inc或LLCimport restrings = ["Banana, orange", "Grape, LLC", "Apple, pear, Inc"][re.sub(", (?!Inc|LLC)",'_',string) for string in strings]#['Banana_orange', 'Grape, LLC', 'Apple_pear, Inc']

LEATH

简单的方法:def replace(str):   x = str.split(', ')   buf = x[0]   for i in range(1, len(x)):       if x[i].startswith('LLC'):         buf += ', ' + x[i]      elif x[i].startswith('Inc'):         buf += ', ' + x[i]      else:         buf += '_' + x[i]   return buf然后尝试replace('a, b, LLC, d')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python