0

Given list like indice = [1, 0, 2] and dimension m = 3, I want to get the mask array like this

>>> import numpy as np
>>> mask_array = np.array([ [1, 1, 0], [1, 0, 0], [1, 1, 1] ])  
>>> mask_array
  [[1, 1, 0],    
   [1, 0, 0],
   [1, 1, 1]]

Given m = 3, so the axis=1 of mask_array is 3, the row of mask_array indicates the length of indice.

For converting the indice to mask_array, the rule is marking the item values whose index is less or equal to the each entry of inside to value 1. For example, indice[0]=1, so the output is [1, 1, 0], given dimension is 3.

In NumPy, are there any APIs which can be used to do this?

1 Answer 1

1

Sure, just use broadcasting with arange(m), make sure to use an np.array for the indices, not a list...

>>> indice = [1, 0, 2]
>>> m = 3
>>> np.arange(m) <= np.array(indice)[..., None]
array([[ True,  True, False],
       [ True, False, False],
       [ True,  True,  True]])

Note, the [..., None] just reshapes the indices array so that the broadcasting works like we want, like this:

>>> indices = np.array(indice)
>>> indices
array([1, 0, 2])
>>> indices[...,None]
array([[1],
       [0],
       [2]])
Sign up to request clarification or add additional context in comments.

1 Comment

I cannot stop accepting your answer, brilliant idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.