NumPy mean()

Created with Sketch.

NumPy mean()

Summary: in this tutorial, you’ll learn how to use the numpy mean() function to calculate the average of elements of an array.

Introduction to the NumPy mean() function

The mean() function returns the average of elements in an array. Here’s the syntax of the mean() function:

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

Code language: Python (python)

In this syntax:

  • a is an array that you want to calculate the average of elements.
  • axis is the axis if specified will return the average of elements on that axis.

To understand more about other parameters and their usages, check out the numpy mean() function documentation.

NumPy mean() function examples

Let’s take some examples of using the mean() function.

1) Using NumPy mean() function on 1-D array example

The following example uses the mean() function to calculate the average of numbers in an array:

import numpy as np

a = np.array([1, 2, 3])
average = np.mean(a)
print(average)

Code language: Python (python)

Output:

2.0

Code language: Python (python)

How it works.

First, create an array that has three numbers:

a = np.array([1, 2, 3])

Code language: Python (python)

Second, calculate the average of elements in the array a using the mean() function:

average = np.mean(a)

Code language: Python (python)

Third, display the average:

print(average)

Code language: Python (python)

The output is 2.0 because (1 + 2 + 3) / 3 = 2.0

2) Using NumPy mean() function on 2-D array example

The following example uses the mean() function to calculate the average of elements on axis-0:

import numpy as np

a = np.array([
[1, 2, 3],
[4, 5, 6]
])
average = np.mean(a, axis=0)
print(average)

Code language: Python (python)

Output:

[2.5 3.5 4.5]

Code language: Python (python)

Summary

  • Use the numpy mean() function to calculate the average of elements in an array.

Leave a Reply

Your email address will not be published. Required fields are marked *