【问题标题】:Csr matrix: How to replace missing value with np.nan instead of 0?Csr 矩阵:如何用 np.nan 而不是 0 替换缺失值?
【发布时间】:2020-12-02 20:09:05
【问题描述】:

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

【问题讨论】:

  • “缺失值”是什么意思? scipy 稀疏矩阵格式存储非零值。其余为 0。句号,句号!我怀疑您是否会在任何 scipy.sparse 文档中发现“缺失”。
  • scipy 稀疏类,尤其是csr 格式,是为数学设计的,尤其是线性代数和矩阵乘法。 nan 填充会以非常不同的方式表现。

标签: python scipy sparse-matrix scipy.stats


【解决方案1】:

这里有一个解决方法:

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

【讨论】:

    【解决方案2】:

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

    如果您真的需要这些 nan,只需操作密集的结果。

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

    【讨论】:

    • Emm,这不是我的期望。我的原始数据包含0,但我不想将其更改为np.nan。我只想用np.nan 填充缺失值。顺便说一句,我无法成功运行您的代码,因为出现了 ValueError: cannot convert float NaN to integer 之类的错误。
    • 好吧,那么 csr_matrix 无法满足您的期望 :-)。 W.R.T.错误,这就是所说的:您的矩阵包含整数,并且没有整数 nan。如果你想要 nans,请指定 dtype=float
    • 这会将所有 0 值转换为 NaN,这不是一个正确的解决方案,因为 OP 想要具有 NaN 值和 0 值的结果。该解决方案需要在解决方案中同时保留零和 NaN。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2019-06-22
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多