在 Numpy 中测试数组值的有限性
numpyserver side programmingprogramming更新于 2025/9/26 11:37:17
要测试数组值的有限性,请使用 Python Numpy 中的 numpy.isfinite() 方法。当 x 不为正无穷大、负无穷大或 NaN 时返回 True;否则返回 false。如果 x 是标量,则返回标量。
此条件通过输入进行广播。在条件为 True 的位置,输出数组将设置为 ufunc 的结果。在其他位置,输出数组将保留其原始值。请注意,如果通过默认的 out=None 创建了未初始化的输出数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库 −
import numpy as np
创建一个包含一些 inf 值的数组 −
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])
显示数组 −
print("数组...
", arr)
获取数组的类型 −
print("
我们的数组类型...
", arr.dtype)
获取数组的维度 −
print("
我们的数组维度...
",arr.ndim)
获取数组中元素的数量 −
print("
元素数量...
", arr.size)
要测试数组值的有限性,请使用 Python Numpy 中的 numpy.isfinite() 方法 −
print("
测试数组的有限性...
",np.isfinite(arr))
示例
import numpy as np
# 创建一个包含一些 inf 值的数组
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])
# 显示数组
print("数组...
", arr)
# 获取数组的类型
print("
我们的数组类型...
", arr.dtype)
# 获取数组的维度
print("
我们的数组维度...
",arr.ndim)
# 获取数组中元素的数量
print("
元素数量...
", arr.size)
# 要测试数组值的有限性,请使用 Python Numpy 中的 numpy.isfinite() 方法
print("
测试数组的有限性...
",np.isfinite(arr))
输出
数组... [ 1. 2. 10. 50. -inf 0. inf] 我们的数组类型…… float64 我们的数组维度…… 1 元素数量... 7 测试数组的有限性... [ True True True True False True False]

