mflowww mflowww - 1 month ago 12
Python Question

How to count the occurrence of certain item in an ndarray in Python?

In Python, I have an ndarray

y

that is printed as
array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])


I'm trying to count how many 0 and how many 1 are there in this array.

But when I type
y.count(0)
or
y.count(1)
, it says
'numpy.ndarray'
object has no attribute 'count'

What should I do?

Answer

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html

check the link for what methods ndarray offers. There is no count function there. The only way is to write the count function yourself. It's easy, just iterate on each element and increment the counter when a given condition is met.