根据您的 numpy 数组的实现方式,您可以使用如下条件操作:
import numpy as np
# Instantiates a sample array.
x = np.array([1, 2, 3, 4, 5])
# Sets the boundary conditions of the operation.
x_min = 2
x_max = 4
# Performs an operation on elements satisfying the boundary conditions.
x[(x_min <= x) & (x <= x_max)] += 10
在这种情况下,在条件操作之前,x = [1, 2, 3, 4, 5]。但是,在条件操作之后,x = [1, 12, 13, 14, 5]。也就是说,它只对满足边界条件的元素进行操作。
你也可以使用 numpy where() 函数来完成同样的事情:
x[np.where((x_min <= x) & (x <= x_max))] += 10
但是,如果您想从数组中完全忽略不需要的值,您可以使用以下任何一种:
x = x[(x_min <= x) & (x <= x_max)]
x = x[np.where((x_min <= x) & (x <= x_max))]
x = np.delete(x, np.where(~(x_min <= x) | ~(x <= x_max)))
分配后,x = [2 3 4],那些满足边界条件的元素。