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 pandas to clean up free form data in a column

I have imported a CSV into a pandas data frame; however, the column I need to use is freeform and in bad shape.

I need to extract the first series of numbers after the word NBU or the first series of numbers in the string. See some examples below:-

nbu 123456
NBU-123456
nbu/ 123456 blah12
123456
123456_123

All of the above should be cleaned to produce 123456. Note that the number of integers returned is based on how many are in a continual sequence; i.e., nbu12 3455 should only return 12.

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

I will then use something like this to fix the data:-

df['col'] = df['col'].str.

>Solution :

A possible solution, which works as follows: It uses str.extract method to extract digits from the col column of df, where in r'(\d+)' the parentheses denote a capturing group, with \d+ meaning one or more digits.

df['col'].str.extract(r'(\d+)')

Output:

        0
0  123456
1  123456
2  123456
3  123456
4  123456
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