(Numpy) List of indexes for a logical array

Input:

  • array length (integer)
  • indexes (Set or List)

Conclusion:

A numpy boolean array that has a value of 1 for indices 0 for others.


Example:

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

Output:

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

Here is my simple implementation:

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

Is there a more elegant way to implement this?

+4
source share
1 answer

One way is to avoid a 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.])
+10
source

All Articles