Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy Array: Slice several values at every step

I am trying to extract several values at once from an array but I can’t seem to find a way to do it in a one-liner in Numpy.

Simply put, considering an array:

a = numpy.arange(10)
> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

I would like to be able to extract, say, 2 values, skip the next 2, extract the 2 following values etc. This would result in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([0, 1, 4, 5, 8, 9])

This is an example but I am ideally looking for a way to extract x values and skip y others.

I thought this could be done with slicing, doing something like:

a[:2:2]

but it only returns 0, which is the expected behavior.

I know I could obtain the expected result by combining several slicing operations (similarly to Numpy Array Slicing) but I was wondering if I was not missing some numpy feature.

>Solution :

You can use a modulo operator:

x = 2 # keep
y = 2 # skip

out = a[np.arange(a.shape[0])%(x+y)<x]

Output: array([0, 1, 4, 5, 8, 9])

Output with x = 2 ; y = 3:

array([0, 1, 5, 6])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading