[英]Finding largest indices of non-zero elements along each axis
I have a 3d numpy array. 我有一个3D numpy数组。 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. 我想沿着数组的三个轴分别找到非零元素元素的最大x
, y
和z
坐标。 How can I do that? 我怎样才能做到这一点?
So for the example below x=1, y=2, z=1 因此,对于下面的示例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)
. 获取非零元素的索引与np.nonzero
并与列堆叠起来np.column_stack
,最终会找到max
沿着列用.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. 看起来好像有一个内置函数np.argwhere
用于获取堆叠在2D
数组中的所有非零元素的索引。 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
使用numpy.nonzero
完成
>>> tuple(coords.max() for coords in numpy.nonzero(A))
(1, 2, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.