![]() |
VOOZH | about |
In NumPy, you can efficiently determine the unique elements of an array and count how many times each element appears. This is useful for analyzing the distribution of values in numerical or categorical datasets.
Let’s explore different methods to count the frequency of unique values in a NumPy array with examples.
np.unique() is widely used method to find unique elements in an array along with their counts. It works for any numeric or string array.
In this example, this code creates a NumPy array of integers and counts the unique values along with their frequency.
Unique Values: [1 3 7 9] Counts: [1 3 2 1]
Explanation:
np.bincount() counts occurrences of non-negative integers efficiently. It is faster than np.unique() for large integer arrays but cannot handle negative numbers or floats.
Here, this code uses np.bincount() to calculate the frequency of elements in an integer array.
Unique Values: [0 1 2 4] Counts: [2 1 3 1]
Explanation:
You can combine the unique values and their counts into a single NumPy array for better visualization.
In this example, this program merges unique elements and their counts into a single NumPy array.
Values and Frequencies: [[2 3 4 5] [2 1 1 2]]
Explanation:
You can transpose the combined array to present the value-count pairs in a more readable column format.
Here, this code transposes the combined array to show [value, count] pairs clearly.
Values and Frequencies in Transpose Form: [[1 2] [2 1] [8 2] [9 1]]
Explanation: Each row shows [value, frequency], making it easy to read and understand.
Counter from Python's collections module counts element occurrences in any iterable. It is easy to use but slower for very large arrays compared to NumPy methods.
In this example, this program uses Counter to count unique elements and display the results.
Unique Values: [10, 15, 5, 20] Counts: [2, 2, 1, 1]
Explanation: