python - 沿每个轴查找非零元素的最大索引

标签 python arrays numpy

我有一个 3d numpy 数组。我想找到沿三个轴的每个非零元素元素的最大 xyz 坐标数组。我怎样才能做到这一点?

因此对于下面的示例 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]]])

最佳答案

使用 np.nonzero 获取非零元素的索引并将它们按列堆叠起来 np.column_stack最后找到 .max(0) 沿列的 max 。实现看起来像这样 -

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

好像有一个内置函数np.argwhere用于获取二维数组中堆叠的所有非零元素的索引。因此,你可以简单地做 -

np.argwhere(A).max(0)

示例运行 -

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])

关于python - 沿每个轴查找非零元素的最大索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33265810/

相关文章:

javascript - 如何在 if/else 或 switch 语句中返回不同的索引位置?

python - 在 Windows 中将创建时间添加十秒

javascript - 数组拼接 - Javascript

php - 如何在 PHP 中组合数组的键和值

python - 矩阵乘法 : Multiply each row of matrix by another 2D matrix in Python

python - fir2 从 matlab 到 python

python - Maya Python 镜像问题

python - 在 Windows 中使用 python 更改目录创建时间 (ctime)

python - 在 django 管理面板中更改列宽

python - 分区组作为 Python 和 NumPy 中的矩阵列表