【问题标题】:For a SciPy sparse matrix, how to get indices of values below a threshold对于 SciPy 稀疏矩阵,如何获取低于阈值的值的索引
【发布时间】:2022-11-03 05:55:27
【问题描述】:

使用条件语句过滤 SciPy 稀疏数组中的值时,如何获取这些值的索引?

我正在尝试使用将条件语句应用于csc_array().data 来获取索引,但它们与csc_array().nonzero() 索引不匹配。这是我面临的问题的一个例子:

import numpy as np
from scipy.sparse import dok_array, csc_array

m = dok_array((1000, 1000))
for i, j in zip(np.random.randint(0, 1000, 100), np.random.randint(0, 1000, 100)):
    m[i, j] = np.random.random()

threshold = 0.3
tmp = csc_array(m)
mask = tmp.data < threshold
i, j = tmp.nonzero()
i_mask, j_mask = i[mask], j[mask]
assert np.alltrue(tmp[i_mask, j_mask] < threshold), "This fails!!!" 

【问题讨论】:

    标签: python scipy sparse-matrix


    【解决方案1】:

    要解决csc_array().datacsc_array().nonzero() 的排序之间的不匹配问题,您可以简单地使用nonzero 索引,如下所示:

    import numpy as np
    from scipy.sparse import dok_array, csc_array
    
    m = dok_array((1000, 1000))
    for i, j in zip(np.random.randint(0, 1000, 100), np.random.randint(0, 1000, 100)):
        m[i, j] = np.random.random()
    
    threshold = 0.3
    tmp = csc_array(m)
    i, j = tmp.nonzero()
    mask = tmp[i, j] < threshold
    i_mask, j_mask = i[mask], j[mask]
    tmp[i_mask, j_mask] = 0
    tmp.eliminate_zeros()
    assert np.alltrue(threshold < tmp.data), "Should not see this!!!" 
    
    m = dok_array(tmp)
    

    【讨论】:

      猜你喜欢
      • 2012-01-15
      • 1970-01-01
      • 2019-12-03
      • 2021-10-30
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 2017-10-23
      相关资源
      最近更新 更多