wabash
wabash

Reputation: 839

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.

Upvotes: 4

Views: 1089

Answers (4)

Enes Aytemiz
Enes Aytemiz

Reputation: 1

You can simply do this to get these numbers in one line:

print([x[i] for i in range(len(x-2)) if (i+2)%4==0 or (i+1)%4==0])

Upvotes: 0

Akshay Sehgal
Akshay Sehgal

Reputation: 19312

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.

Upvotes: 4

Tom
Tom

Reputation: 8790

You could use the modulo % to find the latter 2 elements of every group of four:

>>> x[np.isin(x % 4, [2,3])]

array([ 2,  3,  6,  7, 10, 11, 14, 15, 18, 19])

If your elements aren't a range (and thus their value isn't equal to their index), you could take a new arange:

>>> x = x[::-1] # reverse x
>>> x[np.isin(np.arange(len(x)) % 4, [2,3])]

array([17, 16, 13, 12,  9,  8,  5,  4,  1,  0])

Upvotes: 0

HenriChab
HenriChab

Reputation: 593

You can do something like this:

print([x[i] for i in range(len(x)) if not(((i - 2) % 4) and ((i - 3) % 4))])

Upvotes: 0

Related Questions