Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if there is at least one zero in a multidimensional numpy array

Tags:

python

numpy

I have the following code: There exists a numpy array multidimensional_array which has either has all integers and no zeros, or one zero among many integers:

zeros_list = []   

for line in multidimensional_array:   # if find any zeros, append to list 'zeros'
    for x in line:
        if x.any() == 0:
            zeros_list.append(x)
        else:
            pass

for item in zeros:
    if item == 0:
        sys.stdout.write( 'True')   # if there is a zero, True
    else:
        sys.stdout.write( 'False')  # otherwise, False

Unfortunately, this doesn't run correctly. If there's a zero, it outputs True. If not, nothing happens. Each time I run this within a python script script.py, it should reset. How can I set this to run 'False'?

like image 292
ShanZhengYang Avatar asked Dec 14 '15 23:12

ShanZhengYang


People also ask

How do you check if there is a 0 in a NumPy array?

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 you find the minimum value in NumPy?

For finding the minimum element use numpy. min(“array name”) function.

How do you check if a 2d array has a null column?

If null columns stands for column with its value all equal to 0 , this answer satisfies. However, if null columns stands for column with its value all equal to nan , then my answer satisfies.

How do you find nonzero values in NumPy array?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .


1 Answers

I am sorry. It is a [multidimensional] numpy array. Is there or is there not one zero in a numpy array? That's the test

Alright, that will get us someplace. You can simply issue

0 in multidimensional_array

Demo:

>>> import numpy as np
>>> test1 = np.arange(6).reshape(2,3)
>>> test1
array([[0, 1, 2],
       [3, 4, 5]])
>>> 0 in test1
True
>>> test1[0][0] = 42
>>> test1
array([[42,  1,  2],
   [ 3,  4,  5]])
>>> 0 in test1
False
like image 134
timgeb Avatar answered Oct 08 '22 03:10

timgeb