NumPy nanmean()

The numpy.nanmean() method computes the arithmetic mean along the specified axis and ignores the NaNs (Not a Number).

Example


nanmean() Syntax

The syntax of the numpy.nanmean() method is:

numpy.nanmean(array, axis = None, dtype = None, out = None, keepdims = <no value>, where = <no value>)

nanmean() Arguments

The numpy.nanmean() method takes the following arguments:

  • array - array containing numbers whose mean is desired (can be array_like)
  • axis (optional) - axis or axes along which the means are computed (int or tuple of int)
  • dtype (optional) - the datatype to use in calculation of mean (datatype)
  • out (optional) - output array in which to place the result (ndarray)
  • keepdims (optional) - specifies whether to preserve the shape of the original array (bool)
  • where (optional) - elements to include in the mean (array of bool)

Note: The default values of nanmean() arguments have the following implications:

  • axis = None, i.e. the mean of the entire array is taken.
    • dtype = None, i.e. in the case of integers, float is taken. Otherwise, the calculated mean is of the same datatype as the array elements.
    • out = None, i.e. there is no output array, the array is stored only if the method's return value is assigned to a variable name.
    • By default, keepdims and where will not be passed.

nanmean() Return Value

The numpy.nanmean() method returns the arithmetic mean of the array, ignoring NaNs.


Example 1: Find the Mean of a ndArray

Output

Mean of the entire array: 3.5714285714285716

Mean across axis 0:
[[2. 3.]
 [4. 7.]]

Mean across axis 0 and 1: [3.         4.33333333]

Example 2: Specifying Datatype of Mean of a ndArray

The dtype parameter can be used to control the data type of the output array.

Output

Float64 mean: 3.8 with type float64
Float32 mean: 3.8 with type float32

Note: Using a lower precision dtype can lead to a loss of accuracy.


Example 3: Using Optional keepdims Argument

If keepdims is set to True, the resultant mean array is of the same number of dimensions as the original array.

Output

Dimensions in original array: 2
Without keepdims: [2.5 5.  3. ] with dimensions 1
With keepdims: [[2.5 5.  3. ]] with dimensions 2

Example 4: Using Optional where Argument

The optional argument where specifies which elements to include in the mean.

Output

Mean of entire array: 3.5
Mean of only even elements: 4.0
Mean of  numbers greater than 3: 5.0

Example 5: Using Optional out Argument

The out parameter allows to specify an output array where the result will be stored.

Output

Mean: [2.5 3.5 4.5 nan]

Note: nanmean() returns nan as output only if all elements are nan.