How can you turn an index array into a mask array in Numpy? How can you turn an index array into a mask array in Numpy? numpy numpy

How can you turn an index array into a mask array in Numpy?


Here's one way:

In [1]: index_array = np.array([3, 4, 7, 9])In [2]: n = 15In [3]: mask_array = np.zeros(n, dtype=int)In [4]: mask_array[index_array] = 1In [5]: mask_arrayOut[5]: array([0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0])

If the mask is always a range, you can eliminate index_array, and assign 1 to a slice:

In [6]: mask_array = np.zeros(n, dtype=int)In [7]: mask_array[5:10] = 1In [8]: mask_arrayOut[8]: array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0])

If you want an array of boolean values instead of integers, change the dtype of mask_array when it is created:

In [11]: mask_array = np.zeros(n, dtype=bool)In [12]: mask_arrayOut[12]: array([False, False, False, False, False, False, False, False, False,       False, False, False, False, False, False], dtype=bool)In [13]: mask_array[5:10] = TrueIn [14]: mask_arrayOut[14]: array([False, False, False, False, False,  True,  True,  True,  True,        True, False, False, False, False, False], dtype=bool)


For a single dimension, try:

n = (15,)index_array = [2, 5, 7]mask_array = numpy.zeros(n)mask_array[index_array] = 1

For more than one dimension, convert your n-dimensional indices into one-dimensional ones, then use ravel:

n = (15, 15)index_array = [[1, 4, 6], [10, 11, 2]] # you may need to transpose your indices!mask_array = numpy.zeros(n)flat_index_array = np.ravel_multi_index(    index_array,    mask_array.shape)numpy.ravel(mask_array)[flat_index_array] = 1


As requested, here it is in an answer. The code:

[x in index_array for x in range(500)]

will give you a mask like you asked for, but it will use Bools instead of 0's and 1's.