Counting Occurrences in an ndarray
In numpy, one can encounter the error "numpy.ndarray object has no attribute count" while attempting to use the .count() method to count the occurrence of a specific value in an array.
Using numpy.unique
A solution to this is using numpy.unique(). This function identifies unique values in an array and provides their corresponding counts. For example, to count the number of 0s and 1s in the array y below:
import numpy
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
unique, counts = numpy.unique(y, return_counts=True)
The unique and counts variables will now hold unique values and their counts respectively.
Non-numpy Method
An alternative method that doesn't require numpy is using the collections.Counter class. This class constructs a dictionary that maps elements to their counts. For instance, to count the occurrence of elements in y using Counter:
import collections, numpy
y = np.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(y)
The counter variable will now provide the counts of each unique element in y.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3