Finding Mean, Median, Mode in Python without Libraries


Mean, Median and Mode are very frequently used statistical functions in data analysis. Though there are some python libraries.

Finding Mean

Mean of a list of numbers is also called average of the numbers. It is found by taking the sum of all the numbers and dividing it with the count of numbers. In the below example we apply the sum() function to get the sum of the numbers and th elen() function to get the count of numbers.

Example

num_list = [21, 11, 19, 3,11,5]
# FInd sum of the numbers
num_sum = sum(num_list)
#divide the sum with length of the list
mean = num_sum / len(num_list)
print(num_list)
print("Mean of the above list of numbers is: " + str(round(mean,2)))

Output

Running the above code gives us the following result −

[21, 11, 19, 3, 11, 5]
Mean of the above list of numbers is: 11.67

Finding Median

Median is the middle most value in the list of numbers. In case there are odd count of numbers in the list then we sort the lost and choose the middle most value. If the count is an even number then we choose the two middle most values and take their average as the median.

Example

num_list = [21, 13, 19, 3,11,5]
# Sort the list
num_list.sort()
# Finding the position of the median
if len(num_list) % 2 == 0:
   first_median = num_list[len(num_list) // 2]
   second_median = num_list[len(num_list) // 2 - 1]
   median = (first_median + second_median) / 2
else:
   median = num_list[len(num_list) // 2]
print(num_list)
print("Median of above list is: " + str(median))

Output

Running the above code gives us the following result −

[3, 5, 11, 13, 19, 21]
Median of above list is: 12.0

Finding Mode

Mode is that number in the list which occurs most frequently. We calculate it by finding the frequency of each number present in the list and then choosing the one with highest frequency.

Example

import collections
# list of elements to calculate mode
num_list = [21, 13, 19, 13,19,13]

# Print the list
print(num_list)

# calculate the frequency of each item
data = collections.Counter(num_list)
data_list = dict(data)

# Print the items with frequency
print(data_list)

# Find the highest frequency
max_value = max(list(data.values()))
mode_val = [num for num, freq in data_list.items() if freq == max_value]
if len(mode_val) == len(num_list):
   print("No mode in the list")
else:
   print("The Mode of the list is : " + ', '.join(map(str, mode_val)))

Output

Running the above code gives us the following result −

[21, 13, 19, 13, 19, 13]
{21: 1, 13: 3, 19: 2}
The Mode of the list is : 13
raja
Published on 07-Aug-2019 12:21:42
Advertisements