跳到内容

nanmean

沿给定轴执行跳过 NaN 值的平均操作。默认情况下使用所有轴。

参数

名称 类型 描述 默认值
x SparseArray

要执行约减操作的数组。

必需
axis 联合[int, 可迭代对象[int]]

计算均值的轴。默认使用所有轴。

None
keepdims bool_

是否保留原始数组的维度。

False
dtype dtype

输出数组的数据类型。

None

返回值

类型 描述
COO

归约后的稀疏输出数组。

另请参阅
源代码位于 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)