在 NumPy 中测试数组值的有限性


要测试数组值的有限性,请在 Python NumPy 中使用 **numpy.isfinite()** 方法。如果 x 不是正无穷大、负无穷大或 NaN,则返回 True;否则返回 false。如果 x 是标量,则为标量。

此条件在输入上广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建了一个未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。

步骤

首先,导入所需的库 -

import numpy as np

创建一个包含一些无穷大值的数组 -

arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])

显示数组 -

print("Array...
", arr)

获取数组的类型 -

print("
Our Array type...
", arr.dtype)

获取数组的维度 -

print("
Our Array Dimensions...
",arr.ndim)

获取数组中的元素数量 -

print("
Number of elements...
", arr.size)

要测试数组值的有限性,请在 Python NumPy 中使用 numpy.isfinite() 方法 -

print("
Test array for finiteness...
",np.isfinite(arr))

示例

import numpy as np

# Create an array with some inf values
arr = np.array([1, 2, 10, 50, -np.inf, 0., 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) # To test array values for finiteness, use the numpy.isfinite() method in Python Numpy print("
Test array for finiteness...
",np.isfinite(arr))

输出

Array...
[ 1. 2. 10. 50. -inf 0. inf]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
7

Test array for finiteness...
[ True True True True False True False]

更新于: 2022年2月7日

180 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.