scipy Csr矩阵:如何用np.nan代替0来替换缺失值?

xqkwcwgp  于 2022-11-10  发布在  其他
关注(0)|答案(3)|浏览(181)

看起来csr_matrix默认用0填充缺失值,那么如何用np.nan填充缺失值呢?

from scipy.sparse import csr_matrix
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([0, 2, 3, 4, 5, 6])
csr_matrix((data, (row, col)), shape=(3, 3)).toarray()

输出量:

array([[0, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

预期值:

array([[0, np.nan, 2],
       [np.nan, np.nan, 3],
       [4, 5, 6]])
ezykj2lf

ezykj2lf1#

以下是一个解决方法:

from scipy.sparse import csr_matrix
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([0, 2, 3, 4, 5, 6])

mask = csr_matrix(([1]*len(data), (row, col)), shape=(3, 3)).toarray()
mask[mask==0] = np.nan

csr_matrix((data, (row, col)), shape=(3, 3)).toarray() * mask
qrjkbowd

qrjkbowd2#

这对于csr_matrix是不可能的,因为根据定义,csr_matrix存储非零元素。
如果您 * 真的 * 需要这些nans,只需操纵密集结果。

a=csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
a[a == 0] = np.nan
7fhtutme

7fhtutme3#

def todense_fill(coo: sp.coo_matrix, fill_value: float) -> np.ndarray:
    """Densify a sparse COO matrix. Same as coo_matrix.todense()
    except it fills missing entries with fill_value instead of 0.
    """
    dummy_value = np.nan if not np.isnan(fill_value) else np.inf
    dummy_check = np.isnan if np.isnan(dummy_value) else np.isinf
    coo = coo.copy().astype(float)
    coo.data[coo.data == 0] = dummy_value
    out = np.array(coo.todense()).squeeze()
    out[out == 0] = fill_value
    out[dummy_check(out)] = 0
    return out

相关问题