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

Pandas Dataframe extract number out of inconsistent string

I would like to extract the number out of a column and replace the initial column by the numbers. Thanks for any help.

code:

d = {'col1': [1, 2, 3, 4], 'col2': ['3 A', '4', '7 B', '9F']}
df = pd.DataFrame(data=d)
print(df)

output:

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

   col1 col2
0     1  3 A
1     2    4
2     3  7 B
3     4   9F

desired output:

   col1 col2
0     1    3
1     2    4
2     3    7
3     4    9

>Solution :

Use str.extract:

df['col2'] = df['col2'].str.extract('(\d+)')
# use '^(\d+)' to limit to the leading number

or, for numeric type, combine with pandas.to_numeric:

df['col2'] = pd.to_numeric(df['col2'].str.extract('(\d+)', expand=False),
                           errors='coerce')

output:

   col1 col2
0     1    3
1     2    4
2     3    7
3     4    9
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