Skip to content

nanmean

Performs a NaN skipping mean operation along the given axes. Uses all axes by default.

Parameters:

Name Type Description Default
x SparseArray

The array to perform the reduction on.

required
axis Union[int, Iterable[int]]

The axes along which to compute the mean. Uses all axes by default.

None
keepdims bool_

Whether or not to keep the dimensions of the original array.

False
dtype dtype

The data type of the output array.

None

Returns:

Type Description
COO

The reduced output sparse array.

See Also
Source code in sparse/numba_backend/_coo/common.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def nanmean(x, axis=None, keepdims=False, dtype=None, out=None):
    """
    Performs a `NaN` skipping mean operation along the given axes. Uses all axes by default.

    Parameters
    ----------
    x : SparseArray
        The array to perform the reduction on.
    axis : Union[int, Iterable[int]], optional
        The axes along which to compute the mean. Uses all axes by default.
    keepdims : bool, optional
        Whether or not to keep the dimensions of the original array.
    dtype : numpy.dtype
        The data type of the output array.

    Returns
    -------
    COO
        The reduced output sparse array.

    See Also
    --------
    - [`sparse.COO.mean`][] : Function without `NaN` skipping.
    - [`numpy.nanmean`][] : Equivalent Numpy function.
    """
    assert out is None
    x = asCOO(x, name="nanmean")

    if not (np.issubdtype(x.dtype, np.floating) or np.issubdtype(x.dtype, np.complexfloating)):
        return x.mean(axis=axis, keepdims=keepdims, dtype=dtype)

    mask = np.isnan(x)
    x2 = where(mask, 0, x)

    # Count the number non-nan elements along axis
    nancount = mask.sum(axis=axis, dtype="i8", keepdims=keepdims)
    if axis is None:
        axis = tuple(range(x.ndim))
    elif not isinstance(axis, tuple):
        axis = (axis,)
    den = reduce(operator.mul, (x.shape[i] for i in axis), 1)
    den -= nancount

    if (den == 0).any():
        warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=1)

    num = np.sum(x2, axis=axis, dtype=dtype, keepdims=keepdims)

    with np.errstate(invalid="ignore", divide="ignore"):
        if num.ndim:
            return np.true_divide(num, den, casting="unsafe")
        return (num / den).astype(dtype if dtype is not None else x.dtype)