How do I select a range of two numpy indices?

I have a simple numpy array, and I want to make a separate array that takes every two elements per two indices

For example:

x = np.arange(0,20)

print(x)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

My goal is to get an array of

[2 3 6 7 10 11 14 15 18 19]

How might I do that? I tried this:

print(x[1:len(x)-1:2])

[ 1  3  5  7  9 11 13 15 17]

but I only get every other index.

Answer

You can simply do this using the traditional start:stop:step convention without any modulo by reshaping your array, indexing, and then flattening it back. Try this –

  1. By reshaping it to (-1,2) you create bi-gram sequence
  2. Then you simply start from 1 and step 2 times
  3. Last you flatten it back.
x.reshape(-1,2)[1::2].flatten()
array([ 2,  3,  6,  7, 10, 11, 14, 15, 18, 19])

This should be significantly faster than approaches where mathematical operations are being used to check each value since this is just reshaping and indexing.

Leave a Reply

Your email address will not be published. Required fields are marked *