Reputation: 477
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
Upvotes: 6
Views: 6537
Reputation: 61355
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
Upvotes: 3
Reputation: 29690
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)
Upvotes: 8
Reputation: 477
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?
Upvotes: 1