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

Define a function that extract a float and do operation

I have a column with the following type of values:

enter image description here

I have to define a function that convert column Diameter in float and manage that kind of exception. In particular:

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

  • when is 42×54 then make the operation: sqrt(42^2+54^2)
  • when is Steel then return a NaN value

>Solution :

You can use str.extract with a regex to get the numbers, then square them with pow, sum the columns, and get the square root with numpy.sqrt:

import numpy as np

df['Diameter2'] = np.sqrt(df['Diameter']
                          .str.extract('(\d+)(?:\s*x\s*(\d+))?')
                          .astype(float).pow(2)
                          .sum(axis=1, min_count=1)
                          )

output:

  Diameter  Diameter2
0       44  44.000000
1  42 x 54  68.410526
2    Steel        NaN

regex demo

(\d+)              # capture a number
(?:\s*x\s*(\d+))?  # capture a number (optionally) if preceded by x with optional spaces
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