encode a 0-1 matrix from an integer matrix numpy

Question:

So I have an n*K integer matrix [Note: its a representation of the number of samples drawn from K-distributions (K-columns)]

a =[[0,1,0,0,2,0],
    [0,0,1,0,0,0],
    [3,0,0,0,0,0],
]

[Note: in the application context this matrix basically means that for the i row (sim instance) we drew 1 element from the "distribution 1" (1 in [0,..K]) (a[0,1] = 1) and 2 from the distribution 4(a[0,4] = 2)].

What I need is to generate a 0-1 matrix that represents the same integer matrix but with ones(1). In this case, is a 3D matrix of n*a.max()*K that has a 1 for each sample that is drawn from the distributions. [Note: we need this matrix so we can multiply by our K-distribution sample matrix]

Output

b = [[[0,1,0,0,1,0], # we don't care if they samples are stack 
      [0,0,0,0,1,0],
      [0,0,0,0,0,0]], # this is the first row representation 
     [[0,0,1,0,0,0],
      [0,0,0,0,0,0],
      [0,0,0,0,0,0]], # this is the second row representation 
     [[1,0,0,0,0,0],
      [1,0,0,0,0,0],
      [1,0,0,0,0,0]], # this is the third row representation 

] 

how to do that in NumPy ?
Thanks !

Asked By: Pablo

||

Answers:

from @michael-szczesny comment

a = np.array([[0,1,0,0,2,0],
             [0,0,1,0,0,0],
             [3,0,0,0,0,0],
            ])
b = (np.arange(1, a.max()+1)[:,None] <= a[:,None]).astype('uint8')

print(b)

array([[[0, 1, 0, 0, 1, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0]]], dtype=uint8)
Answered By: Pablo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.