How can I efficiently count the frequency of unique values in a NumPy array?

Patricia Arquette
Release: 2024-10-28 07:03:30
Original
991 people have browsed it

How can I efficiently count the frequency of unique values in a NumPy array?

Obtaining Frequency Counts for Unique Values in a NumPy Array

To efficiently determine the frequency of each unique value within a NumPy array, consider utilizing NumPy's unique function in conjunction with return_counts=True.

<code class="python">import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)</code>
Copy after login

This approach yields a tuple containing two arrays: unique, which holds the unique values present in the original array, and counts, which indicates the respective frequencies of occurrence for each unique value.

For instance, executing the above code with the given input array returns:

[(1, 5), (2, 3), (5, 1), (25, 1)]
Copy after login

indicating that the value 1 appears 5 times, 2 appears 3 times, 5 appears once, and 25 appears once.

Using unique(return_counts=True) offers a substantial performance advantage over SciPy's scipy.stats.itemfreq function for large datasets, as demonstrated in the code snippet below:

<code class="python">In [4]: x = np.random.random_integers(0,100,1e6)

In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop

In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop</code>
Copy after login

The above is the detailed content of How can I efficiently count the frequency of unique values in a NumPy array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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!