-1

Have array like

arr = [1,2,3,4,5,6,7,8,9,10].

How I can get array like this:

[1,2,5,6,9,10]

take 2 elements with step 2(::2)

I try something like arr[:2::2].it's not work

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
iGero
  • 383
  • 1
  • 3
  • 6

1 Answers1

2

[:2::2] is not valid Python syntax. A slice only takes 3 values - start, stop, step. You are trying to provide 4.

Here's what you need to do:

In [233]: arr = np.arange(1,11)                                                               
In [234]: arr                                                                                 
Out[234]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

first reshape to form groups of 2:

In [235]: arr.reshape(5,2)                                                                    
Out[235]: 
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])

now slice to get every other group:

In [236]: arr.reshape(5,2)[::2 ,:]                                                             
Out[236]: 
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])

and then back to 1d:

In [237]: arr.reshape(5,2)[::2,:].ravel()                                                     
Out[237]: array([ 1,  2,  5,  6,  9, 10])

You have to step back a bit, and imagine the array as a whole, and ask how to make it fit the desire pattern.

hpaulj
  • 221,503
  • 14
  • 230
  • 353