【问题标题】:Pandas Regex extract giving different output to re.search?熊猫正则表达式提取物为 re.search 提供不同的输出?
【发布时间】:2020-08-09 06:59:17
【问题描述】:

所以,我正在尝试使用正则表达式从我的 pandas 数据框的一列中提取权重值...由于某种原因,它的提取不正确。

all_data["name"].iloc[0] = "220 grams" # this is purely to show my issue

pattern  = "[0-9]+ ?(gram|mg|Gram|GRAM)"

gram_values = all_data["name"].str.contains(pattern)

re.search(pattern, all_data["name"].iloc[0])

输出是

<re.Match object; span=(0, 8), match='220 gram'>

正如预测的那样,它正在出口 220 克。万岁。

现在,如果我使用 pandas.str.extract 方法...

all_data["name"].str.extract(pattern)

那么输出就是

相同的正则表达式模式,两个不同的输出。那么我到底在做什么错呢?正则表达式字符串如何提取不同的值?

【问题讨论】:

    标签: python regex pandas re


    【解决方案1】:

    Pandas Series.str.extract() 行为在文档中进行了解释,它仅返回 capturing group 内容。

    pat : string
    带有捕获组的正则表达式模式

    您的正则表达式包含单个捕获组 (gram|mg|Gram|GRAM),因此返回其内容。

    要使正则表达式在 Pandas str.extract 中工作,用一个捕获组包装它,并让另一个 group non-capturing

    r"([0-9]+ ?(?:gram|mg|Gram|GRAM))"
    # |        |non-capturing group||
    # |_______ capturing group______|
    

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2020-01-15
      • 2015-10-25
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多