在 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 值的数组 -
arr = np.array([1, 2, 10, 50, -np.nan, 0., np.nan, np.inf])
显示数组 -
print("Array...
", arr)获取数组的类型 -
print("
Our Array type...
", arr.dtype)
获取数组的维度 -
print("
Our Array Dimensions...
",arr.ndim)获取数组中的元素数量 -
print("
Number of elements...
", arr.size)
创建另一个具有相同形状的数组以存储结果 -
arrRes = np.array([5, 5, 5, 5, 5, 5, 5, 5])
要测试数组值是否为 NaN,请在 Python NumPy 中使用 numpy.isnan() 方法。我们将存储结果的新位置是 arrRes -
print("
Test array for NaN...
",np.isnan(arr, arrRes))
检查存储我们结果的新数组的值 -
print("
Result...
",arrRes)示例
import numpy as np
# Create an array with some NaN values
arr = np.array([1, 2, 10, 50, -np.nan, 0., np.nan, np.inf])
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Our Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Our Array Dimensions...
",arr.ndim)
# Get the number of elements in the Array
print("
Number of elements...
", arr.size)
# Create another array with the same shape to store the result
arrRes = np.array([5, 5, 5, 5, 5, 5, 5, 5])
# To test array values for NaN, use the numpy.isnan() method in Python Numpy
# The new location where we will store the result is arrRes
print("
Test array for NaN...
",np.isnan(arr, arrRes))
# Check the value of the new array where our result is stored
print("
Result...
",arrRes)输出
Array... [ 1. 2. 10. 50. nan 0. nan inf] Our Array type... float64 Our Array Dimensions... 1 Number of elements... 8 Test array for NaN... [0 0 0 0 1 0 1 0] Result... [0 0 0 0 1 0 1 0]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP