len(data) - numpy.count_nonzero(data)
There's a builtin for this.
Question
I have the code:
def find_zeros(data):
'''creates a list of the indexes of the zeros in the data'''
zeroidx=np.where(np.any(data==0, axis=1))
print zeroidx
return len(zeroidx)
But the result is:
(array([525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537,
538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550,
551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563,
564, 565], dtype=int64),)
which gives the length 1.
How do I find the length of the array of numbers?
This finds the locations of the zeros. Basically I just want to know how many zeros there are in the data? Is there a better way otherwise?
La solution
len(data) - numpy.count_nonzero(data)
There's a builtin for this.
Autres conseils
Just do check for the zero value and call sum on the resulting boolean array:
(data == 0).sum()
This is a more general solution that can be used for finding any value not just zero and nonzero numbers in the array.
And it even performs slightly but insignificantly better the count_nonzero
(the array length is 100000000):
%timeit (a == 0).sum()
1 loops, best of 3: 249 ms per loop
%timeit len(a) - numpy.count_nonzero(a)
1 loops, best of 3: 326 ms per loop