I have data that I would like to summarize by the mode of a list. When there is more than one mode, I would like to choose from the modes randomly. As I understand them, in a list with multiple modes the scipy and statistics mode functions return the first mode and raise an exception, respectively. I've rolled my own function (as follows), but I'm wondering if there's a better way.
import random
def get_mode(l):
s = set(l)
max_count = max([l.count(x) for x in s])
modes = [x for x in s if l.count(x) == max_count]
return random.choice(modes)
You can use Counter
to do this:
from collections import Counter
from random import choice
def get_mode(l):
c = Counter(l)
max_count = max(c.values())
return choice([k for k in c if c[k] == max_count])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.