Finding the Mode of a List

Finding mode of a list

sorted() sorts your list.

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

Update
Note: This is a very inefficient way of calculating the mode. There are more performant solutions in other answers. This answer is focuses narrowly on what OP asked. Do not use this code in production.

Please also see notes in the comments on other improvements of this code.

find approximate mode from a list python

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

Using SPECIFICALLY reduce() to find the mode of a list of numbers

You could do this

def get_mode(nums):
return reduce(lambda x,y: x if nums.count(x) > nums.count(y) else y, nums)

How to find the statistical mode?

One more solution, which works for both numeric & character/factor data:

Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}

On my dinky little machine, that can generate & find the mode of a 10M-integer vector in about half a second.

If your data set might have multiple modes, the above solution takes the same approach as which.max, and returns the first-appearing value of the set of modes. To return all modes, use this variant (from @digEmAll in the comments):

Modes <- function(x) {
ux <- unique(x)
tab <- tabulate(match(x, ux))
ux[tab == max(tab)]
}


Related Topics



Leave a reply



Submit