Mean, Median, and Mode Using statistics
Module
Here’s an example demonstrating how to calculate each of these:
- Mean: The average of a set of numbers.
- Median: The middle value of a set of numbers.
- Mode: The most frequently occurring value in a set of numbers.
Detailed Explanation and Manual Calculation
Mean
The mean is the sum of all values divided by the number of values.
# List of numbers
data = [10, 20, 20, 30, 40, 50, 50, 50]
# Calculate the mean manually
mean_manual = sum(data) / len(data)
print(f"Mean (manual calculation): {mean_manual}")
Median
The median is the middle value when the data is sorted. If there is an even number of values, the median is the average of the two middle values.
# List of numbers
data = [10, 20, 20, 30, 40, 50, 50, 50]
# Calculate the median manually
data_sorted = sorted(data)
n = len(data)
if n % 2 == 0:
median_manual = (data_sorted[n//2 - 1] + data_sorted[n//2]) / 2
else:
median_manual = data_sorted[n//2]
print(f"Median (manual calculation): {median_manual}")
Mode
The mode is the value that appears most frequently in the data.
from collections import Counter
# List of numbers
data = [10, 20, 20, 30, 40, 50, 50, 50]
# Calculate the mode manually
data_counter = Counter(data)
mode_manual = data_counter.most_common(1)[0][0]
print(f"Mode (manual calculation): {mode_manual}")
Full Example Combining All Calculations
Here is a complete script that includes both the statistics
module functions and manual calculations for mean, median, and mode: