Program 2: Mean, Median and Mode with NumPy
Write a program to calculate mean, median and mode using NumPy.
1Aim
2Program
# Program 2: Calculate mean, median and mode using NumPy
# Marks scored by 15 students in an AI unit test (out of 20).
import numpy as np
marks = np.array([12, 15, 18, 15, 9, 20, 15, 11, 18, 14, 16, 15, 7, 18, 13])
print("Marks :", marks)
print("Number of students :", len(marks))
print()
mean = np.mean(marks)
median = np.median(marks)
# NumPy has no mode() function. np.unique() lists each different value
# once, and return_counts=True says how many times each one occurs.
values, counts = np.unique(marks, return_counts=True)
mode = values[np.argmax(counts)]
print("Mean :", round(mean, 2))
print("Median :", median)
print("Mode :", mode)
print()
print("How often each mark occurs:")
for i in range(len(values)):
print(" ", values[i], ":", counts[i], "time(s)")3Output
The output of a real run, exactly as it appeared.
Marks : [12 15 18 15 9 20 15 11 18 14 16 15 7 18 13]
Number of students : 15
Mean : 14.4
Median : 15.0
Mode : 15
How often each mark occurs:
7 : 1 time(s)
9 : 1 time(s)
11 : 1 time(s)
12 : 1 time(s)
13 : 1 time(s)
14 : 1 time(s)
15 : 4 time(s)
16 : 1 time(s)
18 : 3 time(s)
20 : 1 time(s)4How it works
np.mean(marks)The mean is the average: add all the marks and divide by how many there are.
np.median(marks)The median is the middle value once the marks are sorted. With 15 marks, it is the 8th.
np.unique(marks, return_counts=True)NumPy has no mode() function. np.unique() lists each different mark once, and return_counts=True gives how many times each occurs.
values[np.argmax(counts)]np.argmax() gives the position of the largest count; the value at that position is the mode — the mark that occurs most often.
5Try this
- Add two more 18s to the marks. Which is the mode now?
- Use the statistics module's mode() function and compare.
- Find the mean, median and mode of your own class's marks.
6Viva questions
▸Define mean, median and mode.
Mean is the average, median is the middle value when the data is sorted, and mode is the value that occurs most often.
▸Does NumPy have a mode() function?
No. The mode is found with np.unique() and return_counts, or with the statistics module.
▸Why is the median sometimes better than the mean?
Because one very large or very small value pulls the mean but hardly moves the median.