1

I am trying to run a loop while there are no zeros in my numpy array. was wondering if there was a good way of checking array for zeros rather than going through it line by line.

2
  • 1
    Please show us some code, maybe? What's the shape of your array, for starters? What are you actually doing in the larger scheme of things? Commented Dec 30, 2019 at 19:40
  • 1
    Running a loop with numpy is usually bad design, but you need to show your code. Commented Dec 30, 2019 at 19:42

2 Answers 2

1

You can use numpy.all:

while np.all(myarray != 0):
    dostuff
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative approach can be to use np.count_nonzero:

while np.count_nonzero(arr) == arr.size:
    #your code here

4 Comments

count_nonzero returns an ND array if arr has more than one dimension, so you probably need to flatten arr in the call. Also, OP wants to know if there are no zeros, so doesn't this have to be something like != len(arr)?
@mtrw I am sorry but I think you are mistaken here, count_nonzero always an integer, if the axis is not given, since the default value of the axis is None so it will return an integer even for a multi-dimensional array
Oh, I missed that the call flattens the array internally if axis is left at None - nice.
@mtrw thank you for the second suggestion I think the edit fixes the condition.

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.