Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Numpy) Index list to boolean array

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?

like image 816
lancif Avatar asked May 01 '15 05:05

lancif


People also ask

How do you use boolean indexing in NumPy?

You can index specific values from a NumPy array using another NumPy array of Boolean values on one axis to specify the indices you want to access. For example, to access the second and third values of array a = np. array([4, 6, 8]) , you can use the expression a[np.

How do I return an index to an array in python?

Get the index of elements in the Python loopCreate a NumPy array and iterate over the array to compare the element in the array with the given array. If the element matches print the index.

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

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.])
like image 193
Zero Avatar answered Oct 09 '22 04:10

Zero