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.
-
1Please 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?AKX– AKX2019-12-30 19:40:37 +00:00Commented Dec 30, 2019 at 19:40
-
1Running a loop with numpy is usually bad design, but you need to show your code.Alexander– Alexander2019-12-30 19:42:31 +00:00Commented Dec 30, 2019 at 19:42
Add a comment
|
2 Answers
An alternative approach can be to use np.count_nonzero:
while np.count_nonzero(arr) == arr.size:
#your code here
4 Comments
mtrw
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)?Inder
@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
mtrw
Oh, I missed that the call flattens the array internally if
axis is left at None - nice.Inder
@mtrw thank you for the second suggestion I think the edit fixes the condition.