numpy.mean() is used to calculate the arithmetic mean (average) of numeric data. It can find the mean of all elements in an array or calculate means along specific rows or columns of a multi-dimensional array.
Example: The following example calculates the average value of a list of numbers.
import numpy as np
a = [10, 20, 30, 40]
r = np.mean(a)
print(r)
Output
25.0
Explanation: np.mean(a) adds all values and divides the total by the number of elements to return the average.
Syntax
numpy.mean(a, axis=None, dtype=None, out=None)
Parameters:
- a: Input array of numbers
- axis (optional): None - mean of all elements, 0 - column-wise mean and 1 - row-wise mean
- dtype (Optional): type used while computing mean
- out (Optional): array to store the result
Return Value: Returns the mean value as a scalar or NumPy array, depending on the input and axis.
Examples
Example 1: This example finds the average value of a 1D list using np.mean().
import numpy as np
arr = [20, 2, 7, 1, 34]
res = np.mean(arr)
print(res)
Output
12.8
Explanation: (20 + 2 + 7 + 1 + 34)/5 = 12.8
Example 2: This example shows how to compute the mean of all elements, each column, and each row using axis.
import numpy as np
arr = [[14, 17, 12],
[15, 6, 27],
[23, 2, 54]]
print(np.mean(arr))
print(np.mean(arr, axis=0))
print(np.mean(arr, axis=1))
Output
18.88888888888889 [17.33333333 8.33333333 31. ] [14.33333333 16. 26.33333333]
Explanation: axis=0 computes the mean of each column, while axis=1 computes the mean of each row.
Example 3: This example stores the result of row-wise mean into another array using out.
import numpy as np
arr = [[5, 10, 15],
[3, 6, 9],
[8, 16, 24]]
res = np.zeros(3)
np.mean(arr, axis=1, out=res)
print(res)
Output
[10. 6. 16.]
Explanation: out=res stores the row-wise mean values into res.