Home >Backend Development >Python Tutorial >## How Can I Efficiently Count the Frequency of Unique Values in a NumPy Array?

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

DDD
DDDOriginal
2024-10-26 18:14:30544browse

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

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>

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!

Statement:
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