The numpy.mean() method “calculates the arithmetic mean (average) of the elements in an array” or along a specified axis of a multidimensional array.
Syntax
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
Parameters
- a: The input array or a sequence that can be converted to an array.
- axis: The axis along which the means are computed. By default, it is None, and the mean is calculated for the flattened array.
- dtype: The data type to use in the calculation. By default, it is None, and the data type of the input array is used.
- out: An optional output array to store the result.
- keepdims: If set to True, the reduced axes are left in the result as dimensions with size one. The default value is False.
Example
import numpy as np
# Sample 1D array
arr_1d = np.array([1, 2, 3, 4, 5])
# Calculate the mean of the 1D array
mean_1d = np.mean(arr_1d)
print("Mean of the 1D array:", mean_1d)
# Sample 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Calculate the mean of the 2D array
mean_2d = np.mean(arr_2d)
print("\nMean of the 2D array:", mean_2d)
# Calculate the mean along axis 0 (columns) of the 2D array
mean_axis_0 = np.mean(arr_2d, axis=0)
print("\nMean along axis 0 (columns) of the 2D array:", mean_axis_0)
# Calculate the mean along axis 1 (rows) of the 2D array
mean_axis_1 = np.mean(arr_2d, axis=1)
print("\nMean along axis 1 (rows) of the 2D array:", mean_axis_1)
Output
Mean of the 1D array: 3.0
Mean of the 2D array: 5.0
Mean along axis 0 (columns) of the 2D array: [4. 5. 6.]
Mean along axis 1 (rows) of the 2D array: [2. 5. 8.]
In this example, we calculated the mean of a 1D array, a 2D array, and the means along axis 0 (columns) and axis 1 (rows) of a 2D array using the numpy.mean() method.