简体   繁体   English

计算数组中非零值的范围

[英]Calculate The Extent Of Non-Zero Values In An Array

Suppose I have a 2-D numpy array A , how do I calculate the number of elements between the first non-zero x element and the last non-zero x element. 假设我有一个二维numpy数组A ,如何计算第一个非零x元素和最后一个非零x元素之间的元素数。 So far I'm calculating the position of the index of the first non-zero element using 到目前为止,我正在使用以下方法计算第一个非零元素的索引位置

import numpy as np
A = np.array([[0, 0, 3],[0, 4, 2],[0, 7, 0],[0, 0, 0]])
for row in range(np.size(A,1)):
    if A[:,row].any():
        xMin = row
        break
print(xMin)

I could then do something similar for xMax starting from the end of the array and calculate the difference. 然后,我可以从数组末尾开始为xMax做类似的事情,并计算差值。 The array represents a board and I want to find the range/extent of the items on the board. 该数组代表一个板,我想找到板上项目的范围/程度。 I wonder whether it might be possible using np.nonzero() to find the non-zero elements or stripping the array of non-zero elements. 我想知道是否有可能使用np.nonzero()查找非零元素或剥离非零元素数组。 The simplest idea is to just loop over all the elements of the board and keep track of xMin and xMax but is there a more efficient way to do this? 最简单的想法是仅遍历电路板的所有元素并跟踪xMinxMax但是有没有更有效的方法呢?

Yes, you can do it using np.nonzero() . 是的,您可以使用np.nonzero() The first item is the first occurrence of non-zero items and the last one is the last occurrence. 第一项是非零项目的第一个出现,最后一个是最后一个出现。 Then you can use the shape of your array (length of rows) to calculate number of items in between. 然后,您可以使用阵列的形状(行的长度)来计算介于两者之间的项目数。

In [56]: x, y = A.shape

In [57]: (s, *rest, l),(ss, *rest, ll) = np.nonzero(A)

# without counting start and end
In [58]: (l - s) * y - (ss - ll) - 1
Out[58]: 4

# Counting start and end 
In [59]: (l - s) * y - (ss - ll) + 1
Out[59]: 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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