Issue
There are so many questions around that deal with finding the most common value in an array, but all of them return the "first" element in case of a tie. I need the highest value from the list of tied elements, imagine something like this:
import numpy as np
my_array = [1, 1, 3, 3]
most_common = np.bincount(my_array).argmax()
This gives me 1
, which is obviously not wrong, but I have a tied result here and I want to decide on my own what I want to do in that case. For my application, in case of such a tie I want the highest value from my_array
, which is 3
. How can I do that?
PS: need a Python 2.7 answer... sorry, but can't change that at the moment
Solution
You could apply argmax
to the reversed output of bincount
, and then adjust to take into account the reversal:
In [73]: x
Out[73]: array([3, 0, 2, 3, 1, 0, 1, 3, 2, 1, 1, 2, 1, 3, 3, 4])
In [74]: b = np.bincount(x)
In [75]: b
Out[75]: array([2, 5, 3, 5, 1])
In [76]: most_common = len(b) - 1 - b[::-1].argmax()
In [77]: most_common
Out[77]: 3
Answered By - Warren Weckesser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.