gpt4 book ai didi

python - Csr 矩阵 : How to replace missing value with np. nan 而不是 0?

转载 作者:行者123 更新时间:2023-12-05 04:59:43 26 4
gpt4 key购买 nike

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

最佳答案

解决方法如下:

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

关于python - Csr 矩阵 : How to replace missing value with np. nan 而不是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63387321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com