Numpy:argwhere axis = -1包含值> = 0

时间:2016-03-27 03:31:06

标签: python numpy

我有一个多维数组,其值分为两组,正数(零)或负数。我的目标是获得除最终维度指数以外的所有指数(零包含)。我的例子应该让事情更清楚。

import random
import numpy as np

a = np.full((3,3,2), -1, dtype=np.int32)
for i in range(3):
    x = random.randint(0, 2)
    y = random.randint(0, 2)
    z = random.randint(0, 1)
    a[x][y][z] = random.randint(0, 1)

# example array
#[[[-1, -1],
#  [-1, -1],
#  [-1, -1],],
#
# [[-1, -1],
#  [-1, -1],
#  [ 1, -1],],
#
# [[ 8, -1],
#  [-1, -1],
#  [ 9, -1],]]

# find third dimensions where any value is positive
dimensions = set()
for (x, y, z) in np.argwhere(a >= 0):
    dimensions.add((x, y))

# print dimensions from previous step
for (x, y) in dimensions:
    print a[x][y]

# example output
# [ 1, -1]
# [ 8, -1]
# [ 9, -1]

具体来说,我喜欢做类似下面的事情,但是如果最终维度恰好是全零的话,它会起作用。

for (y, x) in np.argwhere(a.any(axis=-1)):

天真的实施工作正常,但我确信有更好的方法可以解决这个问题。

1 个答案:

答案 0 :(得分:0)

试试这个:

i0, i1, i2 = np.where(a >= 0)

a[i0, i1, :]