Is it possible to get the length of the nonzero elements in a numpy array without iterating over the array or masking the array. Speed is the main goal of calculating the length.
Essentially, something like len(array).where(array != 0).
If it changes the answer, each row will begin with zeros. The array is filled on the diagonal with zeros.
Assuming you mean total number of nonzero elements (and not total number of nonzero rows):
or even better:
This last one,
count_nonzero, seems to behave well when the array is small, too, whereas thesumtrick not so much: