简体   繁体   中英

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. 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. 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. 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?

Yes, you can do it using 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

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