In this tutorial, we will learn how to find the mean of a given dataset in Python using the popular library NumPy. NumPy is a powerful library for numerical computing in Python and provides many useful functions to perform various operations on arrays and matrices.
One such function is to find the arithmetic mean. The arithmetic mean is the sum of the elements divided by the number of elements.
Let’s get started and learn how to find the mean using NumPy.
Step 1: Install NumPy
First, make sure you have NumPy installed on your machine. If not, we can install it using the pip package manager. Just open your terminal/cmd and type the following command:
1 |
pip install numpy |
After installing NumPy, we can use it in our Python code.
Step 2: Import NumPy
To use NumPy library functions, we need to import it into our Python script. To do this, just add the following line at the beginning of your Python script:
1 |
import numpy as np |
This will import NumPy under the alias np
, which is a widely-accepted practice in the Python community.
Step 3: Define the Dataset
Now that we have imported NumPy, let’s define our dataset. Here, we will create a list data
that contains some random values which will be used to find the mean.
1 |
data = [12, 17, 19, 21, 25, 32, 35, 40, 45, 50] |
Feel free to replace these values with your dataset or use variables to store these values.
Step 4: Find Mean Using NumPy
To find the mean of our dataset using NumPy, we simply need to call the np.mean()
function and pass our dataset (list or NumPy array) as an argument.
1 |
mean = np.mean(data) |
This will calculate the mean of our dataset and store it in the variable mean
.
Step 5: Display the Mean
Now that we have the mean of our dataset, let’s display it on the screen. We can do this using the print
function.
1 |
print("Mean of the dataset:", mean) |
This will output the mean of our dataset.
Full Code
1 2 3 4 5 6 |
import numpy as np data = [12, 17, 19, 21, 25, 32, 35, 40, 45, 50] mean = np.mean(data) print("Mean of the dataset:", mean) |
Output
Mean of the dataset: 29.6
Conclusion
In this tutorial, we have learned how to find the mean of a dataset in Python using the NumPy library. We have gone through the installation of NumPy, importing it, defining our dataset, and finding the mean using the np.mean()
function. Finding the mean using NumPy is a simple and efficient way to achieve this task in Python.