Search code examples
pythoncounterpython-itertoolsmode

find approximate mode from a list python


I have a list with values like [62,62,65,67,68,69,3,3,3,1,1,30,30].

If I create a Counter using this value and take the max occurring value, I get it as 3.

But, as you can the values 62-69 are kind of close to each other, and I would like to get an average value of these values as the most occurring one. How can we achieve this in python?


Solution

  • You can group your data into ranges, then find the mode For example, arranging your data in ranges of 10, we get

    >>> l2 = [e//10 for e in l]
    >>> l2
    [6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0, 3, 3]
    

    And mode for that is 6

    >>> Counter(l2).most_common(1)
    [(6, 6)]
    

    So your original data should have the mode close to middle of that range, 6*10+5 = 65