(x, axis=None)
return _apply_func(x, np.nanmedian, nanmedian_sparse, axis=axis)
Equivalent of np.nanmedian that supports sparse or dense matrices.
Equivalent of np.nanmedian that supports sparse or dense matrices.
Equivalent of np . nanmedian that supports sparse or dense matrices .
def nanmedian(x, axis=None):
    """ Equivalent of np.nanmedian that supports sparse or dense matrices. """
    def nanmedian_sparse(x):
        nz = np.logical_not(np.isnan(x.data))
        n_nan = sum(np.isnan(x.data))
        n_nonzero = sum(x.data[nz] != 0)
        n_zeros = np.prod(x.shape) - n_nonzero - n_nan
        if n_zeros > n_nonzero:
            # Typical case if use of sparse matrices make sense
            return 0
        else:
            # Possibly contains NaNs and
            # more nz values than zeros, so allocating memory should not be too problematic
            return np.nanmedian(x.toarray())

    return _apply_func(x, np.nanmedian, nanmedian_sparse, axis=axis)
def nanmedian ( x , axis = None ) : def nanmedian_sparse ( x ) : nz = np . logical_not ( np . isnan ( x . data ) ) n_nan = sum ( np . isnan ( x . data ) ) n_nonzero = sum ( x . data [ nz ] != 0 ) n_zeros = np . prod ( x . shape ) - n_nonzero - n_nan if n_zeros > n_nonzero : # Typical case if use of sparse matrices make sense return 0 else : # Possibly contains NaNs and # more nz values than zeros, so allocating memory should not be too problematic return np . nanmedian ( x . toarray ( ) ) return _apply_func ( x , np . nanmedian , nanmedian_sparse , axis = axis )