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

How do I extract data from a DataFrame using regular expressions?

I am trying to correct data in a DataFrame and am facing a value replacement problem. The original value comes in the format "31 ^" or "54_", I need it to come in the format Integer for example 31.54

frame = pd.DataFrame({'first': [123, '32^'], 'second': [23,'13_']})
frame['first'] = frame['first'].str.extract(r'([0-9]+)', expand=False)


first   second
0   NaN 23
1   32  13_

>Solution :

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

Use Series.str.extract with fillna:

In [679]: frame['first'] = frame['first'].str.extract('(\d+)').fillna(frame['first'])

In [680]: frame['second'] = frame['second'].str.extract('(\d+)').fillna(frame['second'])

In [681]: frame
Out[681]: 
  first second
0   123     23
1    32     13
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