+3 votes
in Programming Languages by (73.2k points)

I use count function to count the occurrence of an item in a list, but when I use this function for numpy array,  it says 'numpy.ndarray' object has no attribute 'count'. Is count function not available with numpy array? What should I do?

>>> y
array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1], dtype=int8)
>>> y.count(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'count'

1 Answer

+2 votes
by (346k points)
selected by
 
Best answer

Yes, count can't be used with numpy array. There are several ways to count the occurrence of an item in a numpy array, but my favorite one is using 'collections.Counter'. It generates a dictionary with items as keys and their counts as values. Have a look at the following example.

>>> import collections
>>> y = np.array(['0', '0', '0', '1', '0', '1', '1','0', '0', '0', '0', '1'])
>>> collections.Counter(y)
Counter({'0': 8, '1': 4})
>>> t=collections.Counter(y)
>>> t['0']
8


...