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
There's a nice trick to do this as a one-liner, too - use the
numpy.in1d
andnumpy.arange
functions like this (the final line is the key part):The downside of this approach is that it's ~10-100x slower than the appropch Warren Weckesser gave... but it's a one-liner, which may or may not be what you're looking for.
Here's one way:
If the mask is always a range, you can eliminate
index_array
, and assign1
to a slice:If you want an array of boolean values instead of integers, change the
dtype
ofmask_array
when it is created:As requested, here it is in an answer. The code:
will give you a mask like you asked for, but it will use Bools instead of 0's and 1's.
For a single dimension, try:
For more than one dimension, convert your n-dimensional indices into one-dimensional ones, then use ravel: