用于 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
广告