简体   繁体   中英

Finding largest indices of non-zero elements along each axis

I have a 3d numpy array. I'd like to find the largest x , y and z co-ordinates of non-zero element elements along each of the three axes of the array. How can I do that?

So for the example below x=1, y=2, z=1

array([[[1, 1, 0],
        [1, 1, 0],
        [0, 0, 0]],

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

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])

Get the indices of non-zero elements with np.nonzero and stack them up in columns with np.column_stack and finally find the max along the columns with .max(0) . The implementation would look something like this -

np.column_stack((np.nonzero(A))).max(0)

Looks like there is a built-in function np.argwhere for getting indices of all non-zero elements stacked in a 2D array. Thus, you can simply do -

np.argwhere(A).max(0)

Sample run -

In [50]: A
Out[50]: 
array([[[1, 1, 0],
        [1, 1, 0],
        [0, 0, 0]],

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

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])

In [51]: np.column_stack((np.nonzero(A))).max(0)
Out[51]: array([1, 2, 1])

In [52]: np.argwhere(A).max(0)
Out[52]: array([1, 2, 1])

Done using numpy.nonzero

>>> tuple(coords.max() for coords in numpy.nonzero(A))
(1, 2, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM