Reputation: 12929
I'd like to form a piece of code that gives a print statement if there is a detection of a nonzero number in an array. The attempt I have is as follows:
if numpy.where(array != 0):
print "NonZero element detected!"
elif numpy.where(array ==0):
print "All elements are zero"
I also know of the numpy.nonzero command but I'd really like to get this if, else style of printed statements working and I'm not sure how to incorporate the python logic properly. I'm more interested in getting the logic working than I am finding zeroes. What I have seems to produced the "NonZero element detected!" statement regardless of whether or not there are non-zeroes in the array. Any there any ideas on how to implement this?
Upvotes: 0
Views: 2581
Reputation: 8068
If you're looking purely for detection of non-zero element in array, why not doing something like this.. or am I missing something?
arr_1 = (1,2,4,6,7,88,9)
arr_2 = (1,2,4,6,0,7,88,9)
print if 0 in arr_1 'Non zero detected' else 'There is no zero in array'
Upvotes: 1
Reputation: 16730
You can use the any
built-in:
Return True if any element of the iterable is true. If the iterable is empty, return False.
if any(elt != 0 for elt in array):
print("Non zero detected")
else:
print("All elements are zero")
As a bonus, if the only elements that evaluates to False
Boolean-wise is 0
, you can simply do:
if any(array):
print("Non zero detected")
else:
print("All elements are zero")
Upvotes: 3
Reputation: 402844
You can create a mask using conditionals:
mask = array == 0
print(mask)
array([ True, False, False, True], dtype=bool)
You can chain this with a .all
or .any
call, depending on your use case. If you want to check whether all elements are zero, you'd do:
if (array == 0).all():
print('All elements are 0!')
Or,
if (array != 0).any():
print('Non-zero elements detected!')
And so on.
You can do the same thing using np.mask
as long as you provide two additional arguments:
mask = np.where(array == 0, True, False)
print(mask)
array([ True, False, False, True], dtype=bool)
Upvotes: 1