3

似乎默认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]])
4

2 回答 2

2

这是一种解决方法:

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
于 2021-03-20T01:59:09.843 回答
0

csr_matrix 不可能,它根据定义存储非零元素。

如果你真的需要那些 nan,只需操纵密集的结果。

a=csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
a[a == 0] = np.nan
于 2020-08-13T06:06:38.210 回答