Python 如何替换稀疏矩阵Scipy中的列
我有一个二维尺寸相同的矩阵a和B A-是一个零矩阵,从B开始,我只取第一列,用B.col[0]替换第一列A.col[0] 我写Python 如何替换稀疏矩阵Scipy中的列,python,matrix,scipy,sparse-matrix,Python,Matrix,Scipy,Sparse Matrix,我有一个二维尺寸相同的矩阵a和B A-是一个零矩阵,从B开始,我只取第一列,用B.col[0]替换第一列A.col[0] 我写 data_sims = np.zeros((data.shape[0],data.shape[1])) data_sims = sparse.csr_matrix(data_sims).tocoo() 我试过这样的smth,但没用 data_sims.getcol(0).toarray = data.getcol(0).toarray() 我甚至试着用hstack,
data_sims = np.zeros((data.shape[0],data.shape[1]))
data_sims = sparse.csr_matrix(data_sims).tocoo()
我试过这样的smth,但没用
data_sims.getcol(0).toarray = data.getcol(0).toarray()
我甚至试着用hstack,但还是出错了
“ValueError:块必须是二维的”,但它们是相同的二维尺寸,我缺少什么?请帮帮我
data_sims = hstack(data.getcol(0).toarray(),data_sims)
可以将列指定给列:
from scipy import sparse
import numpy as np
# Target matrix
A = np.zeros((2, 2))
# Some sparse matrix
B = sparse.csr_matrix([[5, 6], [7, 8]]).tocoo()
# Assign the first column from B into A
A[:, 0] = B.tocsc()[:, 0].todense().ravel()
这张照片是:
[[ 5. 0.]
[ 7. 0.]]
您创建了一个由零组成的二维numpy数组,而不是矩阵或稀疏矩阵
In [782]: x = np.zeros((3,2),int)
In [783]: x.getcol(0)
....
AttributeError: 'numpy.ndarray' object has no attribute 'getcol'
这样的数组没有getcol
方法;这是由稀疏矩阵定义的
In [782]: x = np.zeros((3,2),int)
In [783]: x.getcol(0)
....
AttributeError: 'numpy.ndarray' object has no attribute 'getcol'
您可以通过索引访问数组的列。结果是一个一维数组。如果要设置列,则需要提供兼容的值,例如另一个1d数组或正确长度的列表
In [784]: x[:,0]
Out[784]: array([0, 0, 0])
In [785]: x[:,0] = [1,2,3]
In [786]: x
Out[786]:
array([[1, 0],
[2, 0],
[3, 0]])
稀疏矩阵有一个getcol
:
In [801]: M = sparse.csr_matrix([[1,0],[0,2],[2,0]])
In [802]: M
Out[802]:
<3x2 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in Compressed Sparse Row format>
In [803]: M.getcol(0)
Out[803]:
<3x1 sparse matrix of type '<class 'numpy.int32'>'
with 2 stored elements in Compressed Sparse Row format>
In [804]: M.getcol(0).toarray()
Out[804]:
array([[1],
[0],
[2]], dtype=int32)
In [805]: x[:,0] = M.getcol(0).toarray()
....
ValueError: could not broadcast input array from shape (3,1) into shape (3)
csr
实现索引,因此这也适用于:
In [810]: x[:,0] = M[:,0].toarray().ravel()
对于coo
格式,例如Mo=M.tocoo()
,必须使用getcol
还有其他匹配形状的方法。例如,如果x
是np.matrix
而不是array,则其列选择将是(3,1)
使用列表、x[:,[0]]
或切片进行索引也会生成2d列
在某种程度上,这与最近多次出现的数组/矩阵兼容性问题相同,但稀疏矩阵的使用增加了一个扭曲。简单的“a”方法教学示例
来到这里希望得到答案,并想尝试以下方法。
我很高兴地发现这种“直观的方法”奏效了
输出:
[[1 4 7]
[2 5 8]
[3 6 9]]
[[11 14 17]
[12 15 18]
[13 16 19]]
[[ 1 14 7]
[ 2 15 8]
[ 3 16 9]]
标题听起来像是您试图更改稀疏矩阵中的值。但您的示例尝试将稀疏矩阵中的值写入常规数组。
import numpy as np
import scipy.sparse as ss
m1 = np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
m2 = np.array([[11, 14, 17], [12, 15, 18], [13, 16, 19]])
print(m1, '\n')
print(m2, '\n')
m1 = ss.csc_matrix(m1)
m2 = ss.csc_matrix(m2)
m1 = ss.hstack([m1[:, 0], m2[:, 1], m1[:, 2]])
print(m1.todense())
[[1 4 7]
[2 5 8]
[3 6 9]]
[[11 14 17]
[12 15 18]
[13 16 19]]
[[ 1 14 7]
[ 2 15 8]
[ 3 16 9]]