0

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]

2 Answers 2

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of the reshape you can also use keepdims=1
0

By 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])

2 Comments

Why not use count_nonzero?
Eh... Because I never really use it myself? :P I'll update the answer to include it later, thanks for the suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.