678

How do I count the number of 0s and 1s in the following array?

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]) 

y.count(0) gives:

numpy.ndarray object has no attribute count

1
  • 4
    In this case, it is also possible to simply use numpy.count_nonzero. Commented Mar 31, 2019 at 17:50

32 Answers 32

1
2
-1

Numpy has a module for this. Just a small hack. Put your input array as bins.

numpy.histogram(y, bins=y) 

The output are 2 arrays. One with the values itself, other with the corresponding frequencies.

Sign up to request clarification or add additional context in comments.

2 Comments

isn't 'bins' supposed to be a number?
Yes @johnktejik you're right. This answer does not work.
-5
using numpy.count $ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1] $ np.count(a, 1) 

2 Comments

What's with the dollar signs here?
No such function
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.