Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 0s and how many 1s 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?

like image 470
mflowww Avatar asked Feb 22 '15 22:02

mflowww


People also ask

How do you count occurrences in an array?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do you count occurrences in an array in Python?

Use bincount() to count occurrences of a value in a NumPy array. In python, the numpy module provides a function numpy. bincount(arr), which returns a count of number of occurrences of each value in array of non-negative ints. It returned the count of all occurences of 3 in the array.

How do you count unique values in Ndarray?

To count each unique element's number of occurrences in the numpy array, we can use the numpy. unique() function. It takes the array as an input argument and returns all the unique elements inside the array in ascending order.


Video Answer


1 Answers

a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4]) unique, counts = numpy.unique(a, return_counts=True) dict(zip(unique, counts))  # {0: 7, 1: 4, 2: 1, 3: 2, 4: 1} 

Non-numpy way:

Use collections.Counter;

import collections, numpy a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4]) collections.Counter(a)  # Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1}) 
like image 52
Ozgur Vatansever Avatar answered Nov 01 '22 08:11

Ozgur Vatansever