本文介绍了使用另一个矩阵的索引引用矩阵中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您有一个原始的稀疏矩阵X:

You have an original sparse matrix X:

>>print type(X)
>>print X.todense()
<class 'scipy.sparse.csr.csr_matrix'>
[[1,4,3]
 [3,4,1]
 [2,1,1]
 [3,6,3]]

您有第二个稀疏矩阵Z,它是从X的某些行派生而来的(例如,将值加倍,以便我们可以看到两个矩阵之间的差异).在pseudo-code:

You have a second sparse matrix Z, which is derived from some rows of X (say the values are doubled so we can see the difference between the two matrices). In pseudo-code:

>>Z = X[[0,2,3]]
>>print Z.todense()
[[1,4,3]
 [2,1,1]
 [3,6,3]]

>>Z = Z*2
>>print Z.todense()
[[2, 8, 6]
 [4, 2, 2]
 [6, 12,6]]

使用来自X的原始索引来检索Z中的行的最佳方法是什么.例如,以伪代码:

What's the best way of retrieving the rows in Z using the ORIGINAL indices from X. So for instance, in pseudo-code:

>>print Z[[0,3]]
[[2,8,6]              #0 from Z, and what would be row **0** from X)
 [6,12,6]]            #2 from Z, but what would be row **3** from X)

也就是说,如何使用引用原始矩阵X中原始行位置的索引从Z中检索行?为此,您无论如何都不能修改X(您不能向矩阵X添加索引列),但是没有其他限制.

That is, how can you retrieve rows from Z, using indices that refer to the original rows position in the original matrix X? To do this, you can't modify X in anyway (you can't add an index column to the matrix X), but there are no other limits.

推荐答案

如果原始索引位于数组i中,并且i中的值按升序排列(如您的示例),则可以使用numpy.searchsorted(i,[0,3])在Z中找到与原始X中的索引[0,3]对应的索引.这是IPython会话中的一个演示:

If you have the original indices in an array i, and the values in i are in increasing order (as in your example), you can use numpy.searchsorted(i, [0, 3]) to find the indices in Z that correspond to indices [0, 3] in the original X. Here's a demonstration in an IPython session:


In [39]: X = csr_matrix([[1,4,3],[3,4,1],[2,1,1],[3,6,3]])

In [40]: X.todense()
Out[40]:
matrix([[1, 4, 3],
        [3, 4, 1],
        [2, 1, 1],
        [3, 6, 3]])

In [41]: i = array([0, 2, 3])

In [42]: Z = 2 * X[i]

In [43]: Z.todense()
Out[43]:
matrix([[ 2,  8,  6],
        [ 4,  2,  2],
        [ 6, 12,  6]])

In [44]: Zsub = Z[searchsorted(i, [0, 3])]

In [45]: Zsub.todense()
Out[45]:
matrix([[ 2,  8,  6],
        [ 6, 12,  6]])

这篇关于使用另一个矩阵的索引引用矩阵中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:32