How to reshape a 1-d array in a form array (1,4,5)?

advertisements

I have these vectors :

a = [1,2,3,4]
b = [1,2,3,5]

and I could like to have this at the end :

A = [ [1,0,0,0,0]
      [0,1,0,0,0]
      [0,0,1,0,0]
      [0,0,0,1,0] ]

B = [ [1,0,0,0,0]
      [0,1,0,0,0]
      [0,0,1,0,0]
      [0,0,0,0,1] ]

I have been using np.reshape from python this way:

A = np.reshape(a,(1,4,1))
B = np.reshape(b,(1,4,1))

And it does just partially the job as I have the following result:

A = [[1]
     [2]
     [3]
     [4]]

B = [[1]
     [2]
     [3]
     [5]]

Ideally I would like something like this:

A = np.reshape(a,(1,4,(1,5))

but when reading the docs, this is not possible.

Thanks in advance for your help


Alternatively, numpy can assign value to multiple indexes on rows/columns in one go, example:

In [1]: import numpy as np

In [2]: b = [1,2,3,5]
   ...:
   ...: 

In [3]: zero = np.zeros([4,5])

In [4]: brow, bcol = range(len(b)), np.array(b) -1  # logical transform

In [5]: zero[brow, bcol] = 1

In [6]: zero
Out[6]:
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])