NumPy bincount() Function: Counting Element Occurrences in Python
np.bincount is a function in the NumPy library (imported as np) that counts the occurrences of each non-negative integer in an array and returns an array of the counts.
The function takes an array-like object as its input and returns an array of non-negative integers where the i-th element represents the number of occurrences of the integer i in the input array.
Here is the syntax:
np.bincount(arr, weights=None, minlength=0)
Parameters:
arr: The input array-like object.weights(optional): An array-like object of the same length asarrthat represents the weights associated with each element. This parameter is used to calculate the weighted counts.minlength(optional): The minimum length of the output array. By default, the length is determined by the maximum value in the input array.
Returns:
- An array of non-negative integers where the i-th element represents the number of occurrences of the integer i in the input array.
Example usage:
import numpy as np
arr = [0, 1, 1, 3, 2, 1, 7, 7, 7]
counts = np.bincount(arr)
print(counts)
# Output: [1 3 1 1 0 0 0 3]
In the example above, np.bincount counts the occurrences of each non-negative integer in the arr array and returns an array of counts. The input array [0, 1, 1, 3, 2, 1, 7, 7, 7] has one occurrence of 0, three occurrences of 1, one occurrence of 2, one occurrence of 3, and three occurrences of 7.
原文地址: http://www.cveoy.top/t/topic/pgg1 著作权归作者所有。请勿转载和采集!