## How Can I Efficiently Count the Frequency of Unique Values in a NumPy Array?

DDD
Release: 2024-10-26 18:14:30
Original
448 people have browsed it

##  How Can I Efficiently Count the Frequency of Unique Values in a NumPy Array?

Efficient Frequency Counting for Unique Values in NumPy Arrays

For efficient frequency counting of unique values in a NumPy array, consider utilizing numpy.unique with the return_counts=True option, especially for NumPy versions 1.9 and above. This approach provides both unique values and their respective counts.

<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)

print(np.asarray((unique, counts)).T)  # Output in tuple format</code>
Copy after login

This approach surpasses scipy.stats.itemfreq in terms of efficiency, as demonstrated below:

<code class="python">x = np.random.random_integers(0,100,1e6)

%timeit unique, counts = np.unique(x, return_counts=True)  # 31.5 ms
%timeit scipy.stats.itemfreq(x)  # 170 ms</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
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!