Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying re.search function to column in Python

I have the following Python code (I want the first match of a specific number in a text field):

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)

Wanted output:

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

It doesn't seem to work. When I add a [0] to the regex code, it gives an error...(subjectnr = re.search(r"(\b[4][0-1][0-9][0-9]\b)",column)[0])

Who knows what to do? Thanks in advance!

like image 719
W. Mooi Avatar asked Jun 27 '26 02:06

W. Mooi


1 Answers

You can do this with str.extract. You can also condense your pattern a bit, as I show below.

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

This should be much faster than calling apply.


Details

\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
like image 107
cs95 Avatar answered Jun 28 '26 18:06

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!