How to check if a numpy 2d array is surrounded by zeros

Is there any neat way of checking this is a numpy array surrounded by zeros.

Example:

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

I know I can repeat his wise element to find out, but I wonder if there is any good trick we can use here. The numpy array has float, nxm of arbitrary size.

Any ideas are welcome.

+4
source share
3 answers

You can use numpy.any()to check if there is a nonzero element in the numpy array.

Now, to check whether a two-dimensional array is surrounded by zeros, you can get the first and last columns, as well as the first and last rows, and check if any of them contains a nonzero number.

def zero_surrounded(array):
    return not (array[0,:].any() or array[-1,:].any() or array[:,0].any() or array[:,-1].any())
+4

, :

  • A[[0,-1]] , ;
  • A[1:-1,[0,-1]] , .

, :

if np.all(A[[0,-1]] == 0) and np.all(A[1:-1,[0,-1]] == 0):
    # ...
    pass

2d-, . .

:

def surrounded_zero_dim(a):
    n = a.ndim
    sel = ([0,-1],)
    sli = (slice(1,-1),)
    return all(np.all(a[sli*i+sel] == 0) for i in range(n))

, , , .

+3

, , , (, , "" ) :

surrounded = np.sum(a[1:-1, 1:-1]**2) == np.sum(a**2)
print(surrounded)  # True

a - .

, , . , , , .

+2

Source: https://habr.com/ru/post/1688180/


All Articles