6

Input:

  1. array length (Integer)
  2. indexes (Set or List)

Output:

A boolean numpy array that has a value 1 for the indexes 0 for the others.


Example:

Input: array_length=10, indexes={2,5,6}

Output:

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

Here is a my simple implementation:

def indexes2booleanvec(size, indexes):
    v = numpy.zeros(size)
    for index in indexes:
        v[index] = 1.0
    return v

Is there more elegant way to implement this?

2 Answers 2

13

One way is to avoid the loop

In [7]: fill = np.zeros(array_length)     #  array_length = 10

In [8]: fill[indexes] = 1                 #  indexes = [2,5,6]

In [9]: fill
Out[9]: array([ 0.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.,  0.])
0

Another way to do it (in one line):

np.isin(np.arange(array_length), indexes)

However this is slower than Zero's solution.

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.