[英]Reshape a matrix
I have in my Code the following Matrix: 我的代码中包含以下矩阵:
M=[[1, 1, 0],
[2, 1, 0],
[3, 1, 0],
[4, 1, 3],
[5, 1, 0],
[6, 1, 4],
[7, 1, 4],
[8, 1, 5],
[1, 2, 0],
[2, 2, 2],
[3, 2, 7],
[4, 2, 3],
[5, 2, 0],
[6, 2, 3],
[7, 2, 0],
[8, 2, 5],
[1, 3, 1],
[2, 3, 1],
[3, 3, 0],
[4, 3, 3],
[5, 3, 6],
[6, 3, 5],
[7, 3, 4],
[8, 3, 0]]
And I would like to reshape it into the following one 我想将其重塑为以下内容
new_M=[[0, 0, 0, 3, 0, 4, 4, 5],
[0, 2, 7, 3, 0, 3, 0, 5],
[1, 1, 0, 3, 6, 5, 4, 0]]
I've tried with the following Code: 我已经尝试使用以下代码:
new_M=[]
l=0
for j in range(3):
for k in range(8):
new_M[j][k]=M[l][2]
l=l+1
But I get the following error: IndexError: list index out of range 但是我收到以下错误:IndexError:列表索引超出范围
I'd appreciate a way to fix this Code or a better Code to perform the same Task. 我希望能找到一种方法来修复此代码或执行更好的代码来执行同一任务。 PD: I'd also appreciate a detailed Explanation fo the Code because I'm Kind of new using Python.
PD:我也希望对代码进行详细的解释,因为我很喜欢使用Python。
Thank you so much in Advance. 非常感谢您。
numpy
can do you many wonderful jobs: numpy
可以为您完成许多出色的工作:
import numpy as np
np.array(M)[:, 2].reshape(3,8)
array([[0, 0, 0, 3, 0, 4, 4, 5],
[0, 2, 7, 3, 0, 3, 0, 5],
[1, 1, 0, 3, 6, 5, 4, 0]])
In case the first two columns are actually the 2d-indices: 如果前两列实际上是2d索引:
my_arr = np.array(M)
new_arr = np.zeros((3,8))
np.add.at(new_arr, (my_arr[:,1]-1, my_arr[:,0]-1), my_arr[:,2])
print(new_arr)
[[0. 0. 0. 3. 0. 4. 4. 5.]
[0. 2. 7. 3. 0. 3. 0. 5.]
[1. 1. 0. 3. 6. 5. 4. 0.]]
One option if you want to use the two first columns to construct the ndarray
is to use scipy.sparse.csr_matrix
. 如果要使用前两列来构造
ndarray
则一个选择是使用scipy.sparse.csr_matrix
。
In this case you can build the sparse row matrix by specifying: 在这种情况下,您可以通过指定以下内容来构建稀疏行矩阵:
csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]):
csr_matrix((data,(row_ind,col_ind)),[shape =(M,N)]):
where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].
其中data,row_ind和col_ind满足关系a [row_ind [k],col_ind [k]] = data [k]。
from scipy.sparse import csr_matrix
x = np.array(M)
sp = csr_matrix((x[:,-1], (x[:,1]-1, x[:,0]-1)))
sp.todense()
matrix([[0, 0, 0, 3, 0, 4, 4, 5],
[0, 2, 7, 3, 0, 3, 0, 5],
[1, 1, 0, 3, 6, 5, 4, 0]], dtype=int64)
Note: The indices of both the rows and columns should start at 0
, that's why I'm substracting 1
注意:行和列的索引都应从
0
开始,这就是为什么我要减去1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.