2

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.

Ali
  • 335
  • 1
  • 3
  • 12

3 Answers3

3

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]
gmds
  • 19,325
  • 4
  • 32
  • 58
3

The simplest here seems:

 a = np.array([1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4])
 a.reshape(-1,6)[1:4].ravel()

or if a doesn't chunk well :

period = 6
a.resize(np.math.ceil(a.size/period),period)
a[:,1:4].ravel()
B. M.
  • 18,243
  • 2
  • 35
  • 54
2

Here's a vectorized one with masking -

def take_sliced_regions(a, start, take, skip):
    r = np.arange(len(a))-start
    return a[r%(take+skip)<take]

Sample run -

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

In [91]: take_sliced_regions(a, start=1, take=3, skip=3)
Out[91]: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
Divakar
  • 218,885
  • 19
  • 262
  • 358