Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Regex Extraction of Numbers out of String

I have a dataset and most of the data is cleaned. However, I am having some trouble with extracting a portion of a string.

I am trying to access the first number in a string (which is a sales rank), however, the number includes commas and the number of digits varies. In addition, there are usually some characters before the number, but not always. Here is an example of the string:

[>#1,434,846 in Tools & Home Improvement #1,999,999 in electronics]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sometimes the "[>#" does not appear in the front of the string though. Can anyone help with some quick code to extract the number?

Also, in the case where there are multiple numbers, I only want the first number, the "1,434,846" in this case.

>Solution :

import pandas as pd
df['Col1'] = df['Col1'].str.extract(r'([\d,]+)')  # need to enclose regex pattern in capture group 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading