Python Code Snippet to Return the Mode(s) of a List of Values
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
feed
Post new comment