Getting the first occurrence of a value in an N-dimensional numpy array

别说谁变了你拦得住时间么 提交于 2021-02-10 13:08:10

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/22238031/getting-the-first-occurrence-of-a-value-in-an-n-dimensional-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!