How to Count Occurrences of Elements in a NumPy Array?

Barbara Streisand
Release: 2024-10-20 21:47:02
Original
631 people have browsed it

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>
Copy after login

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}
Copy after login

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>
Copy after login

This approach also returns a dictionary with the same key-value pairs as the numpy.unique method:

Counter({0: 7, 1: 4})
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template