Home > Back-end >  Given an array, how does the count in Numpy add up?
Given an array, how does the count in Numpy add up?

Time:03-11

Given this array:

[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]

How does np.count_nonzero(x < 6) result in 8?

{5, 3, 3, 3, 5, 2, 4} - These are the non-zero values that are less than 6 and the count of them is 7.

np.count_nonzero(x > 6) returns 3. I find 3 values greater than 6 below: {7,9,7}

There are only 10 values in the array that are not 6 or 0, so the individual counts don't add up to 10. 8 3 = 11.

CodePudding user response:

Because x < 6 is not equal to x, but instead it is comparing each element with 6.

import numpy as np
x = np.array([[5,0,3,3], [7,9,3,5],[2,4,7,6]])
print(x < 6)

Output:

array([[ True,  True,  True,  True],
       [False, False,  True,  True],
       [ True,  True, False, False]])

And np.count_nonzero() is equivalent of counting non False (or True) elements in the output which is:

np.count_nonzero(x < 6)
# 8
np.sum(x < 6)
#8

And for the last part, why they don't add up to 11 is because the last element is 6. So:

np.count_nonzero(x < 6)   np.count_nonzero(x > 6)   np.count_nonzero(x == 6) 
# 12
  • Related