0

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?

1
  • where gives you a tuple of arrays, one array per dimension. If there aren't any non-zeros those arrays will have shape (0,), i.e. no elements. So if you use where you need to check the length of one of those arrays. I'd suggest experimenting with where in an interactive session. Looking at its result should make this clearer. Commented Sep 4, 2017 at 21:47

3 Answers 3

3

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")
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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'

1 Comment

Shouldn't it be print "msg1" if 0 in array else "msg2"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.