获取具有至少一个满足某些条件的元素的切片的索引

时间:2019-04-11 13:21:36

标签: numpy multidimensional-array

我有一个形状为(n,a,b)的ndarray A 我想要形状(a,b)的布尔ndarray X,其中

X[i,j]=any(A[:, i, j] < 0)

如何实现?

1 个答案:

答案 0 :(得分:1)

我将使用中间矩阵和sum(axis)方法:

np.random.seed(24)

# example matrix filled either with 0 or -1:
A = np.random.randint(2, size=(3, 2, 2)) - 1

# condition test:
X_elementwise = A < 0

# Check whether the conditions are fullfilled at least once:
X = X_elementwise.sum(axis=0) >= 1

A和X的值:

A = array([[[-1,  0],
        [-1,  0]],

       [[ 0,  0],
        [ 0, -1]],

       [[ 0,  0],
        [-1,  0]]])

X = array([[ True, False],
       [ True,  True]])