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'?
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.
For finding the minimum element use numpy. min(“array name”) function.
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.
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)] .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With