python - 如何对数据框列上的多个短语应用正则表达式?

标签 python regex dataframe

您好,我有一个数据框,我想从以这些短语开头或包含这些短语的每一行中删除一组特定的字符“fwd”、“re”、“RE”。我面临的问题是我不知道如何为每种情况应用正则表达式。

我的数据框如下所示:

      summary 
0 Fwd: Please look at the attached documents and take action 
1 NSN for the ones who care
2 News for all team members 
3 Fwd:RE:Re: Please take action on the action needed items 
4 Fix all the mistakes please 
5 Fwd:Re: Take action on the attachments in this email 
6 Fwd:RE: Action is required 

我想要一个像这样的结果数据框:

          summary 
0 Please look at the attached documents and take action 
1 NSN for the ones who care
2 News for all team members 
3 Please take action on the action needed items 
4 Fix all the mistakes please 
5 Take action on the attachments in this email 
6 Action is required 

为了摆脱“Fwd”,我使用了 df['msg'].str.replace(r'^Fwd: ','')

最佳答案

如果它们可以位于字符串中的任何位置,则可以使用重复模式:

^(?:(?:Fwd|R[eE]):)+\s*
  • ^ 字符串开头
  • (?: 非捕获组
    • (?:Fwd|R[eE]): 匹配 Fwd、Re 或 RE
  • )+ 关闭非捕获组并重复 1+ 次
  • \s* 匹配尾随空格

Regex demo

在替换中使用空字符串。

如果您想匹配所有可能的变体,您还可以使用 re.IGNORECASE 使模式不区分大小写,并使用 (?:fwd|re)

例如

str.replace(r'^(?:(?:Fwd|R[eE]):)+\s*','')

关于python - 如何对数据框列上的多个短语应用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60229899/

相关文章:

python并在if语句中分配变量值

regex - 匹配多行并在Perl正则表达式中打印

Python:从一月到当月动态选择列

python - 如何防止通过点击PYQT中的 slider 来更改 slider 的值?

python - 如何从文件中读取 float ?

regex - PowerShell 正则表达式分组

regex - htaccess 重定向多语言 Drupal 站点的一个域

python - 在 Pandas 数据帧 .loc 中使用 Python 的 `in` 运算符

python - 查找数据框是否是另一个数据框的子集,同时忽略索引

python理解数组乘法行为