numpy
  1. numpy-numpymean

numpy.mean()

The numpy.mean() function in NumPy is used to calculate the arithmetic mean of an array or a segment of an array.

Syntax

The basic syntax for using numpy.mean() function is as follows:

numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)
  • a: Required. The input array to be averaged.
  • axis: Optional. The axis along which to compute the mean. If None, then compute over the whole array.
  • dtype: Optional. The type of the returned array and of the intermediate computation.
  • out: Optional. Alternate output array in which to place the result. The default output is None.
  • keepdims: Optional. If this is set to True, the dimensions of the output will be the same as the input, but with size 1 in any dimensions that have been averaged over.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr))

Output:

3.0

Explanation

In the above example, we first imported the NumPy library as np. Then, we created an array arr with the values [1, 2, 3, 4, 5]. Finally, we used the numpy.mean() function to calculate the arithmetic mean of the array arr, which is 3.0.

Use

The numpy.mean() function is useful in a variety of scientific and mathematical applications, such as data analysis, machine learning, and statistical analysis.

Important Points

  • If the axis parameter is not specified, the numpy.mean() function computes the mean value of the entire array.
  • If the axis parameter is specified, the output will have one fewer dimension than the input array. For example, if an array has shape (3,4,5), and axis=2, the output will have shape (3,4).
  • The dtype parameter can be used to specify the data type of the output. If not specified, the data type is determined by the input array.
  • The keepdims parameter is useful when working with multi-dimensional arrays, as it preserves the original dimensions of the array after the mean has been computed.

Summary

The numpy.mean() function in NumPy is used to calculate the arithmetic mean of an array or a segment of an array. It takes an array as input, and optionally, the axis, dtype, out, and keepdims parameters. The function returns the mean of the input array, or a segment of the array along a specified axis. Its application is essential for many mathematical and machine learning algorithms.

Published on: