In the section below, you’ll observe 3 ways to calculate the Mean in Python.
For each of the methods to be reviewed, the goal is to derive the Mean, given the following values:
8, 20, 12, 15, 4
Method 1: Simple Average Calculation
To start, you can use the following average calculations to derive the Mean:
sum_values = 8 + 20 + 12 + 15 + 4 n = 5 mean = sum_values/n print("The Mean is: " + str(mean))
When you run the code in Python, you’ll get the Mean of 11.8
Method 2: Using a List to get the Mean
Alternatively, you can use a List that contains the values to be averaged:
values = [8, 20, 12, 15, 4] n = len(values) sum_values = 0 for i in values: sum_values = sum_values + i mean = sum_values/n print("The Mean is: " + str(mean))
When you run the code, you’ll get the same Mean of 11.8
Method 3: Using Pandas to get the Mean in Python
You can also derive the Mean using Pandas.
For our example:
import pandas as pd data = {"values": [8, 20, 12, 15, 4]} df = pd.DataFrame(data) mean = df["values"].mean() print("The Mean is: " + str(mean))
As before, you’ll get the Mean of 11.8