Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to convert an array of indices to an array of ones and zeros, given the range? i.e. [2,3] -> [0, 0, 1, 1, 0], in range of 5

I'm trying to automate something like this:

>>> index_array = np.arange(200,300)
array([200, 201, ... , 299])

>>> mask_array = ???           # some function of index_array and 500
array([0, 0, 0, ..., 1, 1, 1, ... , 0, 0, 0])

>>> train(data[mask_array])    # trains with 200~299
>>> predict(data[~mask_array]) # predicts with 0~199, 300~499
share|improve this question
    
scipy has a masked array module. It is related to the question. docs.scipy.org/doc/numpy/reference/maskedarray.html –  K.Chen Sep 3 at 22:57
    
[x in index_array for x in range(500)] sort of does it, but with True and False instead of 1 and 0. –  genisage Sep 3 at 23:03
    
@genisage Can you please make your comment as an answer? I want to choose yours. It's the exact thing I was looking for. Thank you for the answer! –  Efreet Sep 4 at 4:47

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

Here's one way:

In [1]: index_array = np.array([3, 4, 7, 9])

In [2]: n = 15

In [3]: mask_array = np.zeros(n, dtype=int)

In [4]: mask_array[index_array] = 1

In [5]: mask_array
Out[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] = 1

In [8]: mask_array
Out[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_array
Out[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] = True

In [14]: mask_array
Out[14]: 
array([False, False, False, False, False,  True,  True,  True,  True,
        True, False, False, False, False, False], dtype=bool)
share|improve this answer
    
+1 This is a very nice answer too, especially if someone wants their mask_array to be an np.array. –  Efreet Sep 5 at 5:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.