How to Count Occurrences of Elements in NumPy Arrays?

Barbara Streisand
Release: 2024-10-20 21:50:30
Original
830 people have browsed it

How to Count Occurrences of Elements in NumPy Arrays?

Counting Occurrences in NumPy Array

NumPy arrays are used extensively for numerical computations, and a common task is to count the occurrence of specific elements within them. However, unlike lists and other Python data structures, NumPy arrays do not have a built-in count method.

Using NumPy's unique

The numpy.unique function can be employed to determine the unique values in an array and their respective counts. It takes an optional parameter return_counts, which when set to True, returns both the unique values and their corresponding counts. For instance:

<code class="python">import numpy

# Create a NumPy array
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

# Obtain unique values and their counts
unique, counts = numpy.unique(y, return_counts=True)

# Convert the results to a dictionary for ease of access
results = dict(zip(unique, counts))

print(results)  # Output: {0: 7, 1: 4}</code>
Copy after login

Non-NumPy Method: Using collections.Counter

Alternatively, you can use the collections.Counter class from outside NumPy. This class is specifically designed for counting occurrences in any iterable, including NumPy arrays:

<code class="python">import collections

# Use the Counter class to tally the occurrences of each element
counter = collections.Counter(y)

# Print the Counter object to view the occurrences
print(counter)  # Output: Counter({0: 7, 1: 4})</code>
Copy after login

The above is the detailed content of How to Count Occurrences of Elements 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!