Home  >  Article  >  Backend Development  >  How Do I Count Element Occurrences in Numpy Arrays?

How Do I Count Element Occurrences in Numpy Arrays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 21:50:03399browse

How Do I Count Element Occurrences in Numpy Arrays?

Counting Occurrences in Numpy Arrays

In order to determine the frequency of specific elements within a Numpy array, various approaches exist. One common method involves utilizing the numpy.unique function. This function identifies the distinct elements in the array and returns a corresponding array of counts for each unique value.

Consider the following example array:

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

Using numpy.unique:

<code class="python">import numpy

unique, counts = numpy.unique(y, return_counts=True)

print(dict(zip(unique, counts)))</code>

This will output a dictionary with the unique elements (0 and 1) as keys and their corresponding counts as values.

Alternatively, a non-NumPy method using collections.Counter can be employed:

<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 will provide a Counter object with the unique elements as keys and their counts as values.

The above is the detailed content of How Do I Count Element Occurrences in Numpy Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn