Home  >  Article  >  Backend Development  >  How to Count Occurrences of Elements in a NumPy Array?

How to Count Occurrences of Elements in a NumPy Array?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 21:47:02529browse

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!

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