用於 NumPy 中元素級 NaN 測試


若要執行元素級的 NaN 測試,請在 Python Numpy 中使用 numpy.isnan() 方法。如果 x 為 NaN,返回 True,否則返回 false。如果 x 是標量,這是標量。條件在輸入上廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設 out=None 建立了未初始化的 out 陣列,則條件為 False 的位置將保持未初始化狀態。

NumPy 使用 IEEE 浮點二進位制算術標準(IEEE 754)。這意味著非數字不等於無窮大。

步驟

首先,匯入所需的庫 −

import numpy as np

若要執行元素級的 NaN 測試,請在 Python Numpy 中使用 numpy.isnan() 方法。

檢查數字 −

print("Check for NaN? ", np.isnan(1))
print("
Check for NaN? ", np.isnan(0))

檢查浮點數 −

print("
Check for NaN? ", np.isnan(14.)) print("
Check for NaN? ", np.isnan(3.6))

檢查 NaN −

print("
Check for NaN? ", np.isnan(np.nan)) print("
Check for NaN? ", np.isnan(np.NAN))

檢查無窮大 −

print("
Check for NaN? ", np.isnan(np.inf)) print("
Check for NaN? ", np.isnan(np.NINF))

檢查日誌 −

print("
Check for NaN? ", np.isnan(np.log(1))) print("
Check for NaN? ", np.isnan(np.log(2)))

示例

import numpy as np

# To test element-wise for NaN, use the numpy.isnan() method in Python Numpy

print("Check for NaN? ", np.isnan(1))
print("
Check for NaN? ", np.isnan(0)) # Checking for float print("
Check for NaN? ", np.isnan(14.)) print("
Check for NaN? ", np.isnan(3.6)) # Checking for NaN print("
Check for NaN? ", np.isnan(np.nan)) print("
Check for NaN? ", np.isnan(np.NAN)) # Checking for infinity print("
Check for NaN? ", np.isnan(np.inf)) print("
Check for NaN? ", np.isnan(np.NINF)) # Checking for log print("
Check for NaN? ", np.isnan(np.log(1))) print("
Check for NaN? ", np.isnan(np.log(2)))

輸出

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? True

Check for NaN? True

Check for NaN? False

Check for NaN? False

Check for NaN? False

Check for NaN? False

更新於: 08-Feb-2022

600 次訪問

開啟您的 事業

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.