【问题标题】:Extract substrings from pandas rows that starts and ends with a special character从以特殊字符开头和结尾的 pandas 行中提取子字符串
【发布时间】:2021-09-03 04:02:40
【问题描述】:

我有这个 df:

id  description
0   changed status to **In progress** of this task
1   changed status to **Closed** of this task   
2   changed status to **Testing** of this task
3   changed status to **Update** of this task
4   changed status to **Completed** of this task

我想通过从描述列中提取** 之间的子字符串来子集这个df,例如In Progress、Closed、Testing、Update 和Completed。

我按照一些堆栈溢出的解决方案尝试了正则表达式,例如:

import re
re.search('**(.+?)**', df.description)

但是我收到了这个错误:

error: nothing to repeat at position 0

知道如何解决这个问题吗?

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    Pandas 嵌入了正则表达式:

    >>> df['description'].str.extract('\*\*(.*)\*\*')
                 0
    0  In progress
    1       Closed
    2      Testing
    3       Update
    4    Completed
    >>> 
    

    只需使用str.extract 方法。

    【讨论】:

      【解决方案2】:

      您不能将系列传递给re.search。它需要一个字符串。请改用str.extract pandas 方法:

      df.description.str.extract(r'\*\*(.+?)\*\*')
      

      【讨论】:

      • 是的! str.extract 在这里很方便,和我的回答一样! :P
      • 对不起,交叉发帖;)
      • 没关系 :P 我们的表达方式有点不同
      【解决方案3】:

      星号是正则表达式中的特殊字符。如果你想要一个文字星号,你需要用 \ 转义它。

      import re
      re.search('\*\*(.+?)\*\*', df.description)
      

      【讨论】:

      • 谢谢。我得到了错误。 TypeError: expected string or bytes-like object
      猜你喜欢
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2021-06-02
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多