我有一列具有以下型別的值:
我必須定義一個函式來將列直徑轉換為浮點數并管理這種例外。尤其是:
- 什么時候是 42x54 然后進行操作: sqrt(42^2 54^2)
- Steel 何時回傳 NaN 值
uj5u.com熱心網友回復:
您可以使用str.extract
正則運算式來獲取數字,然后將它們與pow
、sum
列平方,并使用 得到平方根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)
)
輸出:
Diameter Diameter2
0 44 44.000000
1 42 x 54 68.410526
2 Steel NaN
正則運算式演示
(\d ) # capture a number
(?:\s*x\s*(\d ))? # capture a number (optionally) if preceded by x with optional spaces
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506827.html