0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This one works also for arrays without ties and still gives the correct result in any case. So I'll go with this one.
1

Not sure how you'd go about solving this with Numpy, as there is no way to alter the tie-breaking logic of argmax, but you can do it with collections.Counter easily:

from collections import Counter

my_array = [1, 1, 3, 3]
counter = Counter(my_array)
most_common, num_occurances = max(counter.most_common(), key=lambda x: (x[1], x[0]))

1 Comment

After the initial euphoria, I just found that this only works in such a very specific case and does not really give me a correct result in case of non-ties. For example, if my_array = [1, 1, 3, 3, 3, 4], the result is 4, which is absolutely wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.