I have a numpy array:
[0, 0, 0, 1, 0, 1]
[1, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 1]
Is there any numpy function that would count, lets say, 0's(or any other element) in every row(or column)? e.g.
[4]
[3]
[4]
Use sum on a boolean masked array
(arr == number).sum(1)
>>> (arr == 0).sum(1)
array([4, 4, 4])
>>> (arr == 1).sum(1)
array([2, 2, 2])
Can always reshape at the end
>>> (arr == 0).sum(1).reshape(-1,1)
array([[4],
[4],
[4]])
keepdims=1By performing a comparison A == 0, numpy returns an array of booleans, which you can then sum over as they are interpreted as 1's and 0's for True and False respectively:
>>> A = np.array([
... [0, 1, 0, 1, 0, 1],
... [1, 0, 0, 0, 0, 1],
... [1, 0, 0, 0, 0, 0],
... ])
>>> np.sum(A == 0, axis=0)
array([1, 2, 3, 2, 3, 1])
>>> np.sum(A == 0, axis=1)
array([3, 4, 5])