在 NumPy 中测试数组值是否为正无穷大或负无穷大


要测试数组是否为正无穷大或负无穷大,请在 Python NumPy 中使用 **numpy.isinf()** 方法。返回与 x 形状相同的布尔数组,在 x == +/-inf 的位置为 True,否则为 False。

NumPy 使用 IEEE 算术二进制浮点数标准 (IEEE 754)。如果第一个参数是标量时提供第二个参数,或者第一个和第二个参数具有不同的形状,则会导致错误。

步骤

首先,导入所需的库 -

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.isinf() 方法 -

print("
Test array for positive or negative infinity...
",np.isinf(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 for positive or negative infinity, use the numpy.isinf() method in Python Numpy print("
Test array for positive or negative infinity...
",np.isinf(arr))

输出

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

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
7

Test array for positive or negative infinity...
[False False False False True False True]

更新于: 2022年2月8日

2K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.