If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In NumPy, you can find unique items and their counts in an array using various functions. The numpy.unique()
function is commonly used to get the unique elements from an array, and the numpy.bincount()
function can be used to count the occurrences of each unique item in the array. Here's how you can find unique items and their counts in NumPy:
Finding Unique Items: To get the unique elements from a NumPy array, you can use the numpy.unique()
function. By default, the function returns the unique elements sorted in ascending order.
Output:
Counting Occurrences of Unique Items: To count the occurrences of each unique item in the array, you can use the numpy.bincount()
function. This function works on non-negative integer arrays and returns the count of occurrences of each non-negative integer value up to the maximum value in the array.
Output:
The result indicates that the value 0 appears 0 times, 1 appears 2 times, 2 appears 2 times, and so on.
Counting Occurrences with numpy.unique()
: Alternatively, you can use the return_counts=True
parameter in numpy.unique()
to directly get the unique items and their counts in a single step.
Output:
These functions are useful for analyzing data and understanding the distribution of unique elements in an array. They are commonly used in data processing and exploratory data analysis tasks.
csharpCopy code
[1 2 3 4 5]
[2 2 2 2 1]
pythonCopy code
import numpy as np
# Create an array with some repeated elements
arr = np.array([1, 2, 3, 2, 4, 1, 5, 4, 3])
# Get the unique elements and their counts
unique_elements, item_counts = np.unique(arr, return_counts=True)
# Output
print(unique_elements)
print(item_counts)
csharpCopy code
[0 2 2 2 2 1]
pythonCopy code
import numpy as np
# Create an array with some repeated elements
arr = np.array([1, 2, 3, 2, 4, 1, 5, 4, 3])
# Get the counts of occurrences of each unique item
item_counts = np.bincount(arr)
# Output
print(item_counts)
csharpCopy code
[1 2 3 4 5]
pythonCopy code
import numpy as np
# Create an array with some repeated elements
arr = np.array([1, 2, 3, 2, 4, 1, 5, 4, 3])
# Get the unique elements from the array
unique_elements = np.unique(arr)
# Output
print(unique_elements)
Comments: 0