Facebook Page Twitter Page LinkedIn Page
× NumPy Tutorial NumPy Resources


The NumPy mean() function is used to compute the arithmetic mean along the specified axis. The mean is calculated over the flattened array by default, otherwise over the specified axis.

Syntax

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

Parameters

a Required. Specify an array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axis Optional. Specify axis or axes along which the means are computed. The default is to compute the mean of the flattened array..
dtype Optional. Specify the data type for computing the mean. For integer inputs, the default is float64. For floating point inputs, it is same as the input dtype..
out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.
keepdims Optional. If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. With default value, the keepdims will not be passed through to the mean method of sub-classes of ndarray, but any non-default value will be. If the sub-class method does not implement keepdims the exceptions will be raised.

Return Value

Returns an array containing the mean values when out=None, otherwise returns a reference to the output array.

Example: mean of all values

In the below example, mean() function is used to calculate mean of all values present in the array.

import numpy as np
Arr = np.array([[10,20],[30, 40]])

print("Array is:")
print(Arr)

#mean of all values
print("\nMean of values:", np.mean(Arr))

The output of the above code will be:

Array is:
[[10 20]
 [30 40]]

Mean of values: 25.0

Example: mean() with axis parameter

When axis parameter is provided, mean is calculated over the specified axes. Consider the following example.

import numpy as np
Arr = np.array([[10,20,30],[70,80,90]])

print("Array is:")
print(Arr)

#mean along axis=0
print("\nMean along axis=0")
print(np.mean(Arr, axis=0))

#mean along axis=1
print("\nMean along axis=1")
print(np.mean(Arr, axis=1))

The output of the above code will be:

Array is:
[[10 20 30]
 [70 80 90]]

Mean along axis=0
[40. 50. 60.]

Mean along axis=1
[20. 80.]

Example: mean() with dtype parameter

The dtype parameter can be provided to get the result in the desired data type.

import numpy as np
Arr = np.array([[10,20],[80,90]])
print("Array is:")
print(Arr)

#mean along axis=0 with dtype=complex
print("\nMean along axis=0 (dtype=complex)")
print(np.mean(Arr, axis=0, dtype=complex))

The output of the above code will be:

Array is:
[[10 20]
 [80 90]]

Mean along axis=0 (dtype=complex)
[45.+0.j 55.+0.j]

❮ NumPy - Functions