0

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

Dirty_Fox
  • 1,611
  • 4
  • 20
  • 24
  • You need to consider that every item in the list a is a categorical value ranging from max(a,b) – Dirty_Fox Aug 25 '16 at 15:36
  • It would be more "pythonic" if the values in `a` and `b` assumed 0-based indexing, so 0 is the first column. Any chance you can make such a change to your code? (It is not essential, but it would be nice. It eliminates a subtraction of 1 in the solution.) – Warren Weckesser Aug 25 '16 at 16:23

2 Answers2

3

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.]])
Anzel
  • 19,825
  • 5
  • 51
  • 52
1

What you're trying to do is not actually a reshape, as you alter the structure of the data. Make a new array with the shape you want:

A = np.zeros(myshape)
B = np.zeros(myshape)

and then index those arrays

n = 0
for i_a, i_b in zip(a, b):
    A[n, i_a - 1] = 1
    B[n, i_b - 1] = 1
    n += 1 

The i_a/i_b - 1 in the assignment is only there to make 1 index the 0th element. This also only works if a and b have the same length. Make this two loops if they are not the same length. There might be a more elegant solution but this should get the job done :)

meetaig
  • 913
  • 10
  • 26