numpy.mean() in Python


In Python numpy.mean() function is used to compute arithmatic mean of the data. You should provide the axis along wich the arithmatic should be counted. If axis is not given then array will be flattened and then avarage will be counted. This function returns avarage of array elements.

Basic Syntax

Following is the basic syntax for numpy.mean() function in Python:

numpy.mean(arr, axis=None, dtype=None, out=None, keepdims=<no value>)

And the parameters are:

Parameter Description
arr Provide the input array.
axis Optional. Axis along which mean will be counted. 0 for cloumns and 1 for rows. If not specified then array will be flattened.
dtype Optional. float64 for integers and for floating point inputs same as input data type.
out Optional. Alternative output array in which result will be placed. Optional parameter if provided then the array must be of same shape as expected output.
keepdims Optional. If provided as true then the axes which are reduces will be returned with result.

 

Return Value

numpy.mean() function returns array containing mean values. When input array is 1 dimesional it will return integer value. If out != NONE then it will return the reference.

Example

Following are the examples for numpy.mean() function.

Example 1

# Python program for demonstration of numpy.mean() function
import numpy as np 

# 2 Dimensional array  
new_array = [[10, 20, 30, 40, 50],   
       [5, 35, 85, 75, 45],  
       [34, 76, 76, 76, 98],
       [23, 90, 45, 82, 19]]  
        
# avearge or mean along the axis = 0 (columns)
print("\n Mean of new_array when axis = 0 : ", np.mean(new_array, axis = 0))  
   
# average or mean when axis = 1 (rows)  
print("\n Mean of new_array when axis = 1 : ", np.mean(new_array, axis = 1)) 
  
# average or mean of the flattened array  
print("\n The mean of new_array when axis = None : ", np.mean(new_array))  

The output for the above program is as given below:

Mean of new_array when axis = 0 :  [ 18. , 55.25, 59. , 68.25, 53. ]
Mean of new_array when axis = 1 : [ 30. , 49. , 72. , 51.8]
The mean of new_array when axis = None : 50.700000000000003

Example 2

# Python program for demonstration of numpy.mean() function

import numpy as np 

# 1Dimensional  array  
new_array = [2, 4, 6, 8, 10] 
  
print("Mean value of new_array : ", np.mean(new_array)) 

The output for the above program is as given below:

Mean value of new_array : 6.0