NumPy nanmean()

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

Example

import numpy as np

# create an array
array1 = np.array([0, np.nan, np.nan, 1, 2, 3, 4, 5, 6, 7])

# calculate the mean of the array mean1 = np.nanmean(array1)
print(mean1) # Output: 3.5

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

import numpy as np

# create an array
array1 = np.array([[[0, 1], 
                    [2, np.NaN]], 
                    
                    [[4, 5], 
                    [6, 7]]])

# find the mean of entire array mean1 = np.nanmean(array1) # find the mean across axis 0 mean2 = np.nanmean(array1, 0) # find the mean across axis 0 and 1 mean3 = np.nanmean(array1, (0, 1))
print('\nMean of the entire array:',mean1) print('\nMean across axis 0:\n',mean2) print('\nMean across axis 0 and 1:',mean3)

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.

import numpy as np

array1 = np.array([[1, np.nan, 3],
                [4, 5, 6]])

# by default int is converted to float result1 = np.nanmean(array1) # get float32 mean result2 = np.nanmean(array1, dtype = np.float32)
print('Float64 mean:', result1, 'with type', result1.dtype) print('Float32 mean:', result2, 'with type', result2.dtype)

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.

import numpy as np

array1 = np.array([[1, np.nan, 3],
                [4, 5, np.nan]])

# keepdims defaults to False result1 = np.nanmean(array1, axis = 0) # pass keepdims as True result2 = np.nanmean(array1, axis = 0, keepdims = True)
print('Dimensions in original array:', array1.ndim) print('Without keepdims:', result1, 'with dimensions', result1.ndim) print('With keepdims:', result2, 'with dimensions', result2.ndim)

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.

import numpy as np

array1 = np.array([[1, 2, 3, np.nan],
                [np.nan, 4, 5, 6]])

# take mean of entire array result1 = np.nanmean(array1) # mean of only even elements result2 = np.nanmean(array1, where = (array1 % 2 == 0)) # mean of numbers greater than 3 result3 = np.nanmean(array1, where = (array1 > 3))
print('Mean of entire array:', result1) print('Mean of only even elements:', result2) print('Mean of numbers greater than 3:', result3)

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.

import numpy as np

array1 = np.array([[1, 2, 3, np.nan],
                [4, 5, 6, np.nan]])

# create an output array
output = np.zeros(4)

# compute mean and store the result in the output array np.mean(array1, out = output, axis = 0)
print('Mean:', output)

Output

Mean: [2.5 3.5 4.5 nan]

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

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community