python - 将 re.search 函数应用于 Python 中的列

标签 python regex pandas

我有以下 Python 代码(我想要文本字段中特定数字的第一个匹配项):

import numpy as np
import pandas

data = {'A': [1, 2, 3], 'B': ['bla 4044 bla', 'bla 5022 bla', 'bla 6045 bla']}
df = pandas.DataFrame(data)

def fun_subjectnr(column):
    column = str(column)
    subjectnr = re.search(r"(\b[4][0-1][0-9][0-9]\b)",column)
    subjectnr1 = re.search(r"(\b[2-3|6-8][0-9][0-9][0-5]\b)",column)
    subjectnr = np.where(subjectnr == "" and subjectnr1 != "", subjectnr1, 
    subjectnr)
    return subjectnr1

df['C'] = df['B'].apply(fun_subjectnr)

想要的输出:

 A    B                C
 1    bla 4044 bla    4044
 2    bla 5022 bla    None
 3    bla 6045 bla    6045

好像不行。当我将 [0] 添加到正则表达式代码时,它给出了一个错误...(subjectnr = re.search(r"(\b[4][0-1][0-9][0-9]\b)",列)[0])

谁知道该怎么做?提前致谢!

最佳答案

您可以使用 str.extract 执行此操作。您还可以稍微压缩您的模式,如下所示。

p = r'\b(4[0-1]\d{2}|(?:[2-3]|[6-8])\d{2}[0-5])\b'
df['C'] = df.B.str.extract(p, expand=False)

df

   A             B     C
0  1  bla 4044 bla  4044
1  2  bla 5022 bla   NaN
2  3  bla 6045 bla  6045

这应该比调用 apply 快得多。


详情

\b                 # word boundary
(                  # first capture group
   4               # match digit 4
   [0-1]           # match 0 or 1
   \d{2}           # match any two digits
|
   (?:             # non-capture group (prevent ambiguity during matching)
       [2-3]       # 2 or 3
       |           # regex OR metacharacter
       [6-8]       # 6, 7, or 8
   )
   \d{2}           # any two digits
   [0-5]           # any digit b/w 0 and 5
)
\b

关于python - 将 re.search 函数应用于 Python 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923327/

相关文章:

python - 如何将发布者证书添加到 Cx_freeze msi 包?

python - 在 pytesseract 中运行示例代码

python - TensorFlow 2.0 : Eager execution of training either returns bad results or doesn't learn at all

c# - 什么是优化我的正则表达式匹配的最佳方式

python - 如何计算两个时间戳的小时差并排除周末

python - 在方法执行之前和之后做一些事情

java - 这是正常的 Java 正则表达式行为吗?

java - Java:正则表达式不匹配

python - 如何在 for 循环中附加 Pandas 数据框中的行?

python - 从特定字符串开始读取python中的文件