Mean Median Mode in Python
Mean, Median, and Mode in Python
In statistics, the mean, median, and mode are measures of central tendency that describe the center of a data distribution. You can easily calculate these using Python's built-in functions or libraries such as statistics.
1. Mean
The mean (or average) is the sum of all values divided by the number of values.
Formula:
Where:
is each individual value
is the number of values
Example: Calculating Mean in Python
import statistics# Datadata = [1, 2, 3, 4, 5]# Calculate meanmean_value = statistics.mean(data)print("Mean:", mean_value)2. Median
The median is the middle value of a dataset when the values are sorted in ascending order. If the number of values is even, the median is the average of the two middle values.
Steps to find the median:
Sort the data.
If the number of values is odd, the median is the middle value.
If the number of values is even, the median is the average of the two middle values.
Example: Calculating Median in Python
import statistics# Datadata = [1, 2, 3, 4, 5]# Calculate medianmedian_value = statistics.median(data)print("Median:", median_value)3. Mode
The mode is the value that appears most frequently in a dataset. If there are multiple values that appear with the same highest frequency, the dataset is multimodal. If no number repeats, the dataset has no mode.
Example: Calculating Mode in Python
import statistics# Datadata = [1, 2, 2, 3, 4, 5]# Calculate modemode_value = statistics.mode(data)print("Mode:", mode_value)Handling Multimodal Data
If your dataset has more than one mode, the statistics.mode() function will raise an error. To handle multimodal data (where there are multiple modes), you can use statistics.multimode(), which returns all modes as a list.
Example: Multimodal Data
import statistics# Data (multimodal)data = [1, 2, 2, 3, 3, 4, 5]# Calculate modesmodes = statistics.multimode(data)print("Modes:", modes)Using NumPy for Mean, Median, and Mode
Alternatively, you can use NumPy for mean and median, and SciPy for mode.
Example: Using NumPy and SciPy
import numpy as npfrom scipy import stats# Datadata = [1, 2, 2, 3, 3, 4, 5]# Calculate mean using NumPymean_value = np.mean(data)# Calculate median using NumPymedian_value = np.median(data)# Calculate mode using SciPymode_value = stats.mode(data)[0][0]print("Mean:", mean_value)print("Median:", median_value)print("Mode:", mode_value)Summary
Mean: Average of all values. Use
statistics.mean()ornumpy.mean().Median: Middle value in sorted data. Use
statistics.median()ornumpy.median().Mode: Most frequent value(s). Use
statistics.mode()orscipy.stats.mode().
These statistical measures are useful for summarizing a dataset and understanding its central tendency.