Python Code Snippet to Return the Mode(s) of a List of Values

13 Oct 2009
Posted by Jeet Sukumaran

The following code snippet will return the mode(s) of a list of values, using the specified bin size. If "bin_size" is set to "None", then values are not binned.

#! /usr/bin/env python
 
from operator import itemgetter
 
def mode(values, bin_size=0.1):
    bins = {}
    for v in values:
        if bin_size is not None:
            idx = int(round(float(v)/bin_size))
        else:
            idx = v
        if idx in bins:
            bins[idx] += 1
        else:
            bins[idx] = 1                    
    sorted_bins = sorted(bins.items(), key=itemgetter(1), reverse=True)
    max_count = sorted_bins[0][1]
    results = [(sorted_bins[i][0] * bin_size) for i in xrange(len(sorted_bins)) if sorted_bins[i][1] >= max_count]
    return results 

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a biological visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.