Finding the most frequent value in a NumPy array
Start your free 7-days trial now!
Consider the following array:
array([1, 2, 2, 2, 3, 3])
To find the most frequent value:
a = np.array([1,2,2,2,3,3])freq = np.bincount(a)np.argmax(freq)2
Note here that:
bincounts(~)returns an array with the number of occurrences of each number in the range 0 ~ largest number in the array
argmax(~)then allows us to find the index position of the value with the most occurrences as counted by
bincount(~), which is just the most frequent number itself
This method will only work when we are dealing with an array containing non-negative integers as
bincounts(~) will raise a
ValueError if it encounters negative values.