Python Mode

The mode is the most frequent observation in a data sample, to simplify you can say that is the most common number in a list

Before I will show you how to use python mode function, let's understand how it works first

First you need to find out what is the most common nr. You can have 1 or more common numbers in a list

Most common number in data list is 1

data  = [1,2,3,4,1,2,3,1]

Let's get the total count of all numbers and store it in a dict

#define an empty dict
data_count = {}
# take each number from data list and use the data_count dict to count it
for nr in data:
 #if is not the first time I add to data_count then it means data_count exist so I can add 1
 if nr in data_count:
	 data_count[nr] += 1
	 # else data[nr] does not exist, so let's start by putting 1
	 data_count[nr] = 1

Now print data_count dict

You can see that 1 is repeating 3 times, 2 is repeating 2 times, 3 is repeating 2 times and 4 only once

1 is most frequent, so 1 is the mode

As I said keep in mind that you can have more then a single mode for example

data  = [1,2,1,2,3]

in this case you can see that 1 and 2 is the mode

The list it happens to be numbers but it can be any data, even string

Python mode with statistics library

In order to simplify your life you should use statistics. Statistics is a buildin python library, all you have to do is to make sure you import it

Import statistics
#if you want to return multiple modes then you can use the multimode method
the_mode = statistics.multimode(data)
#if you want to get the first single mode
the_mode = statistics.mode(data)

Python mode with scipy

You can use scipy if you have an older version of python

Make sure you install the scipy before you use it

#pip install scipy

from scipy import stats
data = [0,1,8,9,5,3,10,2,2,5]

The mode method will return the mode and the count of the mode

ModeResult(mode=array([2]), count=array([2]))
In order to visit this site you must accept the terms and conditions available at this page