Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending steps for slicing numpy arrays

Tags:

python

numpy

My question is similar to this: subsampling every nth entry in a numpy array

Let's say I have an array as given below: a = [1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4....]

How can I extend the slice such that I slice three elements at specific intervals? I.e. how can I slice 2s from the array? I believe basic slicing does not work in this case.

like image 775
Ali Avatar asked Jul 08 '26 05:07

Ali


1 Answers

You can do this through individual indexing.

We want to start from the element at index 1, take 3 elements and then skip 3 elements:

a = np.array([1, 2, 2, 2, 3, 4, 1, 2, 2, 2, 3, 4, 1, 2, 2, 2, 3, 4])

start = 1
take = 3
skip = 3

indices = np.concatenate([np.arange(i, i + take) for i in range(start, len(a), take + skip)])

print(indices)
print(a[indices])

Output:

[ 1  2  3  7  8  9 13 14 15]
[2 2 2 2 2 2 2 2 2]
like image 91
gmds Avatar answered Jul 10 '26 18:07

gmds