Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将re.search函数应用于列_Python_Regex_Pandas - Fatal编程技术网

在Python中将re.search函数应用于列

在Python中将re.search函数应用于列,python,regex,pandas,Python,Regex,Pandas,我有以下Python代码(我想要文本字段中特定数字的第一个匹配): 想要的输出: 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]) 谁知道该怎么办?提前谢

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

想要的输出:

 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

你能解释一下你是如何得到这个输出的吗?你应该使用
Series.str.findall
。我已经尝试了findall,但我不想要所有匹配项,只想要第一个匹配项……好的,然后
Series.str.extract
。我的问题是,你到底想做什么?为什么第二个结果没有?我想要匹配的第一个匹配项(特定格式的数字),所以第二个不是正确的格式数字(bc第一个数字是5)。我会尝试做这个系列。str.extract,谢谢!如果答案中缺少什么,请告诉我。如果没有,请考虑标记它被接受。非常感谢。谢谢你的回答和正则表达式的建议,它是有效的(我减少了我的代码量:)!
\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