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
s and how many 1
s are there in this array.
But when I type y.count(0)
or y.count(1)
, it says
numpy.ndarray
object has no attributecount
What should I do?
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 .
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.
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With