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.

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.