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
How to Access the Child Classes of an Object in Django Without Knowing the Name of the Child Class
Generating a List of Random Numbers, Summing to 1
Finding Median of List in Python
Running Selenium with Headless Chrome Webdriver
How to Decrypt Openssl Aes-Encrypted Files in Python
How to Count Occurrence of Unique Values Inside a List
Most Efficient Way of Making an If-Elif-Elif-Else Statement When the Else Is Done the Most
Finding Multiple Occurrences of a String Within a String in Python
How to Find All the Subsets of a Set, with Exactly N Elements
Function for Factorial in Python
What Is the Quickest Way to Http Get in Python
Differencebetween Contiguous and Non-Contiguous Arrays
How to Convert a Dataframe to a Dictionary
Read and Write CSV Files Including Unicode with Python 2.7
Remove Punctuation from Unicode Formatted Strings
Local () Variable Referenced Before Assignment
How to Overload _Init_ Method Based on Argument Type
What Does 'Valueerror: Cannot Reindex from a Duplicate Axis' Mean