How To Find Mean In Python Using Numpy

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:

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:

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.

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.

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.

This will output the mean of our dataset.

Full Code

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.