How Do I Count Element Occurrences in Numpy Arrays?

Mary-Kate Olsen
Release: 2024-10-20 21:50:03
Original
398 people have browsed it

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

Using numpy.unique:

<code class="python">import numpy

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!