compute mode python code example
Example 1: how to get median mode average of a python list
>>> import statistics
>>> statistics.median([3, 5, 1, 4, 2])
3
>>> statistics.median([3, 5, 1, 4, 2, 6])
3.5
Example 2: calculate mode in python
from collections import Counter
def calculate_mode(n):
c = Counter(n)
num_freq = c.most_common()
max_count = num_freq[0][1]
modes = []
for num in num_freq:
if num[1] == max_count:
modes.append(num[0])
return modes
def calculate_mode(n):
c = Counter(n)
mode = c.most_common(1)
return mode[0][0]
Example 3: my_mode() python
>>> from collections import Counter
>>> def my_mode(sample):
... c = Counter(sample)
... return [k for k, v in c.items() if v == c.most_common(1)[0][1]]
...
>>> my_mode(["male", "male", "female", "male"])
['male']
>>> my_mode(["few", "few", "many", "some", "many"])
['few', 'many']
>>> my_mode([4, 1, 2, 2, 3, 5])
[2]
>>> my_mode([4, 1, 2, 2, 3, 5, 4])
[4, 2]