的代码
np.diagonal
是:
return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
ndarray
.
In [33]: from scipy import sparse
In [34]: M = sparse.csr_matrix(np.eye(3))
In [35]: M
Out[35]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>
In [36]: M.A # right
Out[36]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
In [37]: np.asanyarray(M) # wrong
Out[37]:
array(<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>, dtype=object)
正确的使用方法
np.对角线
In [38]: np.diagonal(M.A)
Out[38]: array([1., 1., 1.])
但没必要这样。
M
已经有一个
diagonal
方法:
In [39]: M.diagonal()
Out[39]: array([1., 1., 1.])
np.sum
In [40]: M.sum(axis=0)
Out[40]: matrix([[1., 1., 1.]])
In [41]: np.sum(M, axis=0)
Out[41]: matrix([[1., 1., 1.]])
一般来说,尽量使用
sparse
numpy
功能正常工作。
是建立在
努比
努比
稀疏