Numpy 使用另一个矩阵的索引引用矩阵中的行

Numpy 使用另一个矩阵的索引引用矩阵中的行,numpy,scipy,Numpy,Scipy,您有一个原始稀疏矩阵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]] 使用X中的原始索引检索Z中的行的最佳方法是什么。例如,在伪代码中: 也就是说,如何使用引用原始矩阵X中原始行位置的索引从Z检索行?为此,无论如何都不能修改X(不能向矩阵X添加索引列),但没有其他限制 如果在数组i

您有一个原始稀疏矩阵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]]
使用X中的原始索引检索Z中的行的最佳方法是什么。例如,在伪代码中:


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

如果在数组
i
中有原始索引,并且
i
中的值是按递增顺序排列的(如您的示例所示),则可以使用numpy.searchsorted(i[0,3])在Z中查找与原始X中的索引[0,3]相对应的索引。以下是IPython会话中的演示:

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]]) 在[39]中:X=csr_矩阵([1,4,3],[3,4,1],[2,1,1],[3,6,3]) 在[40]中:X.todense() 出[40]: 矩阵([[1,4,3], [3, 4, 1], [2, 1, 1], [3, 6, 3]]) 在[41]中:i=数组([0,2,3]) In[42]:Z=2*X[i] 在[43]中:Z.todense() 出[43]: 矩阵([[2,8,6], [ 4, 2, 2], [ 6, 12, 6]]) [44]中:Zsub=Z[searchsorted(i[0,3])] 在[45]:Zsub.todense()中 出[45]: 矩阵([[2,8,6], [ 6, 12, 6]])
如果数组
i
中有原始索引,并且
i
中的值按递增顺序排列(如示例中所示),则可以使用numpy.searchsorted(i[0,3])在Z中查找与原始X中的索引[0,3]相对应的索引。以下是IPython会话中的演示:

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]]) 在[39]中:X=csr_矩阵([1,4,3],[3,4,1],[2,1,1],[3,6,3]) 在[40]中:X.todense() 出[40]: 矩阵([[1,4,3], [3, 4, 1], [2, 1, 1], [3, 6, 3]]) 在[41]中:i=数组([0,2,3]) In[42]:Z=2*X[i] 在[43]中:Z.todense() 出[43]: 矩阵([[2,8,6], [ 4, 2, 2], [ 6, 12, 6]]) [44]中:Zsub=Z[searchsorted(i[0,3])] 在[45]:Zsub.todense()中 出[45]: 矩阵([[2,8,6], [ 6, 12, 6]]) 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]])