2

我有一些像这样的稀疏矩阵

>>>import numpy as np
>>>from scipy.sparse import *
>>>A = csr_matrix((np.identity(3)))

>>>print A
  (0, 0)    1.0
  (1, 1)    1.0
  (2, 2)    1.0

为了更好地理解A是这样的:

>>>print A.todense()
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

我希望有一个操作员(让我们称之为op1(n))这样做:

>>>A.op1(1)
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]

=> 使最后一n列成为第一列n,所以

>>>A == A.op1(3)  
true

. 是否有一些内置解决方案(编辑:)再次返回稀疏矩阵?解决方案roll

X = np.roll(X.todense(),-tau, axis = 0)
print X.__class__

返回

<class 'numpy.matrixlib.defmatrix.matrix'>
4

2 回答 2

4

scipy.sparse没有roll,但你可以模拟它hstack

from scipy.sparse import *
A = eye(3, 3, format='csr')
hstack((A[:, 1:], A[:, :1]), format='csr')    # roll left
hstack((A[:, -1:], A[:, :-1]), format='csr')  # roll right
于 2012-07-30T11:17:47.260 回答
1
>>> a = np.identity(3)
>>> a
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> np.roll(a, -1, axis=0)
array([[ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.]])
>>> a == np.roll(a, 3, axis=0)
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
于 2012-07-29T19:19:23.773 回答