Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check is numpy 2d array "surrounded" by zeros

Is there any neat way to check is numpy array surrounded by zeros.

Example:

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

I know I can iterate it element wise to find out but I wonder is there any nice trick we can use here. The numpy array is of floats, n x m of arbitrary size.

Any ideas are welcome.

like image 952
ad1v7 Avatar asked Oct 25 '17 19:10

ad1v7


People also ask

How do you check if a NumPy array is all zeros?

In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy. all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value.

How do I check if an array is 2D NumPy?

Look for array. shape: if it comes like (2,) means digit at first place but nothing after after comma,its 1D. Else if it comes like (2,10) means two digits with comma,its 2D.

What is the use of the zeros () function in NumPy array?

Python numpy. zeros() function returns a new array of given shape and type, where the element's value as 0.

Are NP arrays zero indexed?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

You can use numpy.any() to test if there is any non-zero element in numpy array.

Now, to test if a 2D array is surrounded by zeroes, you can get first and last columns as well as first and last rows and test if any of those contains a non-zero number.

def zero_surrounded(array):
    return not (array[0,:].any() or array[-1,:].any() or array[:,0].any() or array[:,-1].any())
like image 114
Pranjal Jain Avatar answered Nov 14 '22 23:11

Pranjal Jain