Lpng
Lpng

Reputation: 119

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

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.

Thank you so much in Advance.

Upvotes: 2

Views: 137

Answers (2)

yatu
yatu

Reputation: 88226

One option if you want to use the two first columns to construct the ndarray is to use 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)]):

where data, row_ind and col_ind satisfy the relationship 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

Upvotes: 1

Chris
Chris

Reputation: 29742

numpy can do you many wonderful jobs:

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:

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.]]

Upvotes: 4

Related Questions