We know that arithmetic mean is the sum of all the elements divided by the total number of elements. So in this article, we are going to learn how to find the mean of the elements in a NumPy array. We are going to use the numpy.mean() function to find the mean of elements along a single axis and also along multiple axes. So let’s begin!
Syntax of the numpy.mean function
numpy.mean(a,axis=None, dtype=None, out=None, keepdims= None)
|a||Denotes array whose mean is to be calculated|
|axis||Denotes axis or axes along which mean is to be calculated|
|dtype||The data type is used in calculating the mean. The default type is float 64|
|out||Output array to store the result|
|keepdims||This parameter takes boolean values. If it is True then the axes that are present on the left are reduced.|
Mean of a Numpy Array – All Elements
In this, an array will be taken as an input and simply the mean of all the elements will be calculated. For example:
import numpy as np A = np.array([[3, 6], [4, 8]]) output = np.mean(A) print(output)
The mean, in this case, will be calculated as follows:
Mean: (3+6+4+8)/4 = 5.25
Mean of a Numpy Array – Elements Along The Axis
In this case, we will take an input array and we will calculate the mean of the array along an axis. Suppose if we pass o to the axis parameter, all other elements of the axes will remain as it is. Only the mean of the elements which are along axis 0 will be calculated.
import numpy as np A = np.array([[3, 6], [4, 8]]) output = np.mean(A, axis=0) print(output)
Here, the elements of the axis zero are [3,6] and [4,8]. Hence, the mean will be calculated as follows:
Mean = ([3,6] + [4,8]) /2
Mean of Elements along Multiple Axes in a Numpy Array
In this case, we will calculate the mean of a NumPy array along multiple axes. We will take axes 0 and 1 for calculating the mean.
import numpy as np A = np.array([[[3, 6], [4, 8]], [[5, 9], [7, 1]]]) output = np.mean(A, axis=(0, 1)) print(output)
- ([3,6], [4,8]) and ([5,9], [7,1]) are the elements present along axis = 0.
- ([3,6] ,[4,8] ,[5,9],[7,1]) are the elements along axis=1
Mean will be calculated as follows:
Mean = ([3,6] + [4,8] + [5,9] + [7,1])/4
= [(3+4+5+7)/4 , (6+8+9+1)/4]
= [4.75 , 6]
In summary, we learned how to calculate the mean of an entire array, the mean along a single axis and mean along multiple axes. Hope you find this article useful.