Define a function that extract a float and do operation
Question:
Answers:
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*xs*(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
(d+) # capture a number
(?:s*xs*(d+))? # capture a number (optionally) if preceded by x with optional spaces
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*xs*(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
(d+) # capture a number
(?:s*xs*(d+))? # capture a number (optionally) if preceded by x with optional spaces