Gabriel
Gabriel

Reputation: 42349

Fast way of turning a list of indexes into a boolean mask

This is a really simple question but I've not found a simple answer. Say you have a large array, a list of indexes into that array, and you want to generate a boolean mask using those indexes.

import numpy as np

# A large array
arr = np.random.uniform(0., 1., 500000)

# A list of indexes (much larger in real code)
idx = [89, 3455, 3, 26789]

# The boolean mask
msk = []
for _ in range(len(arr)):
    if _ in idx:
        msk.append(True)
    else:
        msk.append(False)
msk = np.array(msk)

The for block above works, but gets slow for large idx arrays. What would be a fast way to achieve this? I know np.where() can be used the other way around (boolean into indexes), can it be used here also?

Upvotes: 5

Views: 1543

Answers (1)

jimakr
jimakr

Reputation: 604

there is a much simpler way to do this using numpy zeros and the indexes.

msk = np.zeros(arr.shape, dtype=np.bool)
msk[idx] = True

It is efficient for large arrays

Upvotes: 8

Related Questions