mean() Function of NumPy Library in Python (3 Examples)
In this article, I’ll illustrate how to apply the mean function of the NumPy library in the Python programming language.
The article contains three examples for the application of the mean function of the NumPy library. To be more precise, the article contains these content blocks:
Let’s do this…
Example Data & Add-On Libraries
We first need to load the NumPy library:
import numpy as np # Import NumPy library in Python
Now, we can create a NumPy array as shown below:
my_array = np.array([[1, 2, 3], [4, 5, 6]]) # Create example array print(my_array) # Print example array # [[1 2 3] # [4 5 6]]
Example 1: Mean of All Values in NumPy Array
This example demonstrates how to get the mean of all values in a NumPy array.
For this task, we can apply the mean function of the NumPy library as shown below:
print(np.mean(my_array)) # Get mean of all array values # 3.5
The previous output shows our result, i.e. the mean value of all elements in our array is 3.5.
Example 2: Mean of Columns in NumPy Array
In Example 2, I’ll show how to find the means for each column in a NumPy array.
For this task, we have to specify the axis argument within the mean command to be equal to 0:
print(np.mean(my_array, axis = 0)) # Get mean of array columns # [2.5 3.5 4.5]
Example 3: Mean of Rows in NumPy Array
In this example, I’ll explain how to calculate the mean value of a NumPy array by row.
To accomplish this, we have to set the axis argument of the mean function to 1:
print(np.mean(my_array, axis = 1)) # Get mean of array rows # [2. 5.]
Video, Further Resources & Summary
Do you need more explanations on the examples of this article? Then you may want to have a look at the following video on my YouTube channel. In the video, I illustrate the Python code of this tutorial.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Additionally, you could have a look at some of the related articles on my website:
- Calculate Mean in Python
- Mean of Columns & Rows of pandas DataFrame
- Calculate Mean by Group in Python
- Python Programming Examples
In this Python tutorial you have learned how to use the mean function of the NumPy library. If you have additional questions, tell me about it in the comments.