Home > Article > Backend Development > How to Count Occurrences of Elements in a NumPy Array?
Counting Occurrences of Items in an ndarray
To count the occurrence of specific values within a NumPy array, various methods are available.
Using the numpy.unique function:
<code class="python">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) print(dict(zip(unique, counts)))</code>
This approach generates a dictionary with unique values as keys and their corresponding counts as values. In the example above, it would return:
{0: 7, 1: 4}
Alternatively, one can employ a non-NumPy method using collections.Counter:
<code class="python">import collections, numpy y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]) counter = collections.Counter(y) print(counter)</code>
This approach also returns a dictionary with the same key-value pairs as the numpy.unique method:
Counter({0: 7, 1: 4})
The above is the detailed content of How to Count Occurrences of Elements in a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!