Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the value of multiple maximas in an array in python

Tags:

python

numpy

I have an array

a =[0,  0, 15, 17, 16, 17, 16, 12, 18, 18]

I am trying to find the element value that has max count. and if there is a tie, I would like all of the elements that have the same max count.

as you can see there are two 0, two 16, two 17, two 18 one 15 and one 12 so i want something that would return [0, 16, 17, 18] (order not important but I do not want the 15 or the 12)

I was doing np.argmax(np.bincount(a)) but argmax only returns one element (per its documentation) so I only get the 1st one which is 0

I tried np.argpartition(values, -4)[-4:] that works, but in practice I would not know that there are 4 elements that have the same count number! (maybe I am close here!!! the light bulb just went on !!!)

like image 976
Roland Avatar asked Dec 31 '15 21:12

Roland


People also ask

How do you find the max of two arrays in Python?

maximum() function is used to find the element-wise maximum of array elements. It compares two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned.


Video Answer


1 Answers

You can use np.unique to get the counts and an array of the unique elements then pull the elements whose count is equal to the max:

import numpy as np

a = np.array([0, 0, 15, 17, 16, 17, 16, 12, 18, 18])

un,  cnt = np.unique(a, return_counts=True)

print(un[cnt == cnt.max()])
[ 0 16 17 18]

un are the unique elements, cnt is the frequency/count of each:

In [11]: a = np.array([0, 0, 15, 17, 16, 17, 16, 12, 18, 18])

In [12]: un,  cnt = np.unique(a, return_counts=True)

In [13]: un, cnt
Out[13]: (array([ 0, 12, 15, 16, 17, 18]), array([2, 1, 1, 2, 2, 2]))

cnt == cnt.max() will give us the mask to pull the elements that are equal to the max:

In [14]: cnt == cnt.max()
Out[14]: array([ True, False, False,  True,  True,  True], dtype=bool)
like image 191
Padraic Cunningham Avatar answered Oct 30 '22 05:10

Padraic Cunningham