How to get the value of multiple maxims in an array in python

I have an array

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

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

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

I did np.argmax(np.bincount(a)) , but argmax returns only one element (for its documentation), so I only get the 1st one, which is 0

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

+6
source share
3 answers

You can use np.unique to get the counts and an array of unique elements, then pull the elements whose count is 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 - unique elements, cnt - frequency / counter of each of them:

 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 a mask to pull out elements that are equal to max:

 In [14]: cnt == cnt.max() Out[14]: array([ True, False, False, True, True, True], dtype=bool) 
+8
source

A bit unrealistic, but you can achieve this using Counter and itemgetter :

 from collections import Counter from operator import itemgetter a =[0, 0, 15, 17, 16, 17, 16, 12, 18, 18] counter_list = Counter(a).most_common() max_occurrences = max(counter_list, key=itemgetter(1))[1] answer = [item[0] for item in counter_list if item[1] == max_occurrences] print(answer) 

Output

 [0, 16, 17, 18] 
0
source

Here is a neat solution:

 from collections import Counter import numpy as np a = np.array([0, 0, 15, 17, 16, 17, 16, 12, 18, 18]) freq_count = Counter(a) high = max(freq_count.values()) res = [key for key in freq_count.keys() if freq_count[key]==high] 

Output: [0 16 17 18]

Note: output order is not guaranteed

0
source

All Articles