Regex Search for entire column in pandas dataframe

Viewed 1062

I want to EXTRACT B0153R2A9I from urls in a column in dataframe. e.g. 'http://www.example.com/zs/B0153R2A9I'

I found this code in a reddit group -

import re
search = re.search(r'B[A-Z0-9]{9}', url)
print(search.group(0))

While this appears to work for one link, when I try to apply this for a column like this -

import re
df['code'] = re.search(r'B[A-Z0-9]{9}', "", df['pro_link'])

df['pro_link'] column has all the links. df['code'] is the new column to be created.

I get this error TypeError: 'Series' objects are mutable, thus they cannot be hashed.

1 Answers

You can use

df['code'] = df['pro_link'].str.extract(r'/(B[A-Z0-9]{9})$')

See the regex demo. Details:

  • / - a / char
  • ( - start of a capturing group:
    • B - a B char
    • [A-Z0-9]{9} - nine ASCII uppercase letters or digits
  • ) - end of the capturing group (it is necessary for Series.str.extract to actually return anything)
  • $ - end of string.
Related