Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the mode of a list

Tags:

python

mode

You can use the max function and a key. Have a look at python max function using 'key' and lambda expression.

max(set(lst), key=lst.count)

You can use the Counter supplied in the collections package which has a mode-esque function

from collections import Counter
data = Counter(your_list_in_here)
data.most_common()   # Returns all unique items and their counts
data.most_common(1)  # Returns the highest occurring item

Note: Counter is new in python 2.7 and is not available in earlier versions.


Python 3.4 includes the method statistics.mode, so it is straightforward:

>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
 3

You can have any type of elements in the list, not just numeric:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
 'red'

Taking a leaf from some statistics software, namely SciPy and MATLAB, these just return the smallest most common value, so if two values occur equally often, the smallest of these are returned. Hopefully an example will help:

>>> from scipy.stats import mode

>>> mode([1, 2, 3, 4, 5])
(array([ 1.]), array([ 1.]))

>>> mode([1, 2, 2, 3, 3, 4, 5])
(array([ 2.]), array([ 2.]))

>>> mode([1, 2, 2, -3, -3, 4, 5])
(array([-3.]), array([ 2.]))

Is there any reason why you can 't follow this convention?


There are many simple ways to find the mode of a list in Python such as:

import statistics
statistics.mode([1,2,3,3])
>>> 3

Or, you could find the max by its count

max(array, key = array.count)

The problem with those two methods are that they don't work with multiple modes. The first returns an error, while the second returns the first mode.

In order to find the modes of a set, you could use this function:

def mode(array):
    most = max(list(map(array.count, array)))
    return list(set(filter(lambda x: array.count(x) == most, array)))