How to calculate mean in Numpy?

Let’s learn how to calculate mean in Numpy Python library. Calculating the mean is a fundamental operation in statistics and data analysis, and NumPy provides efficient tools for this purpose.
numpy mean calculation

Mean in Numpy

To calculate mean in Numpy it is enough to use mean built-in function offered by Numpy library.

import numpy as np

my_array = np.array([1, 56, 55, 15, 0])

mean = np.mean(my_array)

print(f"Mean equals: {mean}")

The mean function calculates the average value of all the elements in the array.

See also  How to calculate harmonic mean in Python?

You can also use the axis parameter to calculate the mean along a specific axis of the array. For example, to calculate the mean of each column in the array, you would use the following code:

mean_by_column = np.mean(my_array, axis=0)


This code will return an array with two elements, the mean of the first column and the mean of the second column.

Other parameters of Numpy mean function

The mean function in Numpy has several other parameters that can be used to customize the output.

  • axis: The axis along which the mean will be calculated. The default value is None, which means that the mean will be calculated over the entire array.
  • dtype: The data type of the output array. The default value is the same as the data type of the input array.
  • keepdims: If set to True, the output array will have the same dimensions as the input array, except along the axis dimension. The default value is False.
See also  How to Generate Random Integers in Range with Numpy

For example, the following code will calculate the mean of each column in the array and return an array with the same dimensions as the input array:

import numpy as np

my_array = np.array([
    [1, 56, 55],
    [15, 0, 9]

mean_by_column = np.mean(my_array, axis=0, keepdims=True)


This code calculates the mean of each column in a two-dimensional array and returns a row vector with these mean values, maintaining the order from the original array.

See also  How to uninstall Numpy?