在 Python 中查找 numpy 范围内的元素

pythonserver side programmingprogramming更新于 2025/10/11 11:24:17

有时在使用 numpy 库处理数据时,我们可能需要过滤掉特定范围内的某些数字。这可以通过使用 numpy 中可用的一些内置方法来实现。

使用 and 运算符

在这种方法中,我们采用一个 numpy 数组,然后对其应用 logical_and 函数。numpy 中的 where 子句也用于应用 and 条件。结果是一个数组,显示了满足所需范围条件的元素的位置。

import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# 打印初始数组
print("给定数组:", A)

# 范围 6 到 15
res = np.where(np.logical_and(A >= 6, A <= 15))

# 结果
print("带条件的数组:", res)

输出

运行上述代码得到以下结果 −

给定数组:[ 5 9 11 4 31 27 8]
带条件的数组: (array([1, 2, 6], dtype=int32),)

使用 *

在此方法中,我们使用 * 运算符。它将结果作为实际值而不是数组中值的位置给出。

import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# 打印初始数组
print("给定数组: ", A)

# 范围 6 到 15
res = A [ (A >=6) * (A <= 15)]

# 结果
print("带条件的数组: ", res)

输出

运行上述代码得到以下结果 −

给定数组:[ 5 9 11 4 31 27 8]
带条件的数组:[ 9 11 8]

相关文章


有用资源