2

I have seen this question, but want to reduce the array created from mask = array == value

mask = array([[[ True,  True,  True],
               [False,  True,  True]],

              [[False,  True,  True],
               [False,  True,  True]],

              [[False, False,  True],
               [False,  True,  True]]])

which results in

where(mask) = (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2]),
               array([0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1]),
               array([0, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2]))

and I want to reduce it to an array of the first occurrences of True

array([[0, 1],
       [1, 1],
       [2, 1]])

but can't work out how to go about this from the output of numpy.where. Can anyone help me out?

Community
  • 1
  • 1
bountiful
  • 814
  • 1
  • 8
  • 22
  • 1
    If your array has 3 dimensions, shouldn't the first occurrence of True be `array([[0],[0],[0]])`? What does "an array of the first occurrences" mean? – wflynny Mar 06 '14 at 23:05
  • One solution could be with `np.argmax` possibly with an axis defined. – M4rtini Mar 06 '14 at 23:17

1 Answers1

2

Actually, it's as simple as this:

np.argmax(mask, 2)

Example:

In [15]: %paste
mask = array([[[ True,  True,  True],
               [False,  True,  True]],

              [[False,  True,  True],
               [False,  True,  True]],

              [[False, False,  True],
               [False,  True,  True]]])

## -- End pasted text --

In [16]: np.argmax(mask, 2)
Out[16]:
array([[0, 1],
       [1, 1],
       [2, 1]], dtype=int64)
M4rtini
  • 13,186
  • 4
  • 35
  • 42