6

How do you count the amount of zero rows of a numpy array?

array = np.asarray([[1,1],[0,0],[1,1],[0,0],[0,0]])

-> has three rows with all zero's, hence should give 3

Took me sometime to figure out this one and also couldn't find an answer on SO

3 Answers 3

8

You could also leverage the "truthiness" of non-zero values in an array.

np.sum(~array.any(1))

i.e., sum the rows where none of the values in said row are truthy (and hence are all zero)

Sign up to request clarification or add additional context in comments.

Comments

3

You can use np.all if you're sure that the rows will have all zeros.

 # number of rows which has non-zero elements
In [33]: sum(np.all(arr, axis=1))
Out[33]: 2

# invert the mask to get number of rows which has all zero as its elements
In [34]: sum(~np.all(arr, axis=1))
Out[34]: 3

1 Comment

This is incorrect for cases where a row contains at least one zero but not all zeros.
1
import numpy as np

array = np.array([[1,1],[0,0],[1,1],[0,0],[0,0]])

non_zero_rows = np.count_nonzero((array != 0).sum(1))   # gives 2
zero_rows = len(array) - non_zero_rows                  # gives 3

Any better solutions?

Comments

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.