32

I'm new to programming and I need a program, that can select all odd rows and all even columns of a Numpy array at the same time in one code. here is what I tried:

>In [78]: a

>Out[78]:
>array([[ 1,  2,  3,  4,  5],
>       [ 6,  7,  8,  9, 10],
>       [11, 12, 13, 14, 15],
>       [16, 17, 18, 19, 20]])
>
>In [79]: for value in range(a.shape[0]):
>     if value %2 == 0:
>        print a[value,:]

>[1 2 3 4 5]
>[11 12 13 14 15]
>
>In [82]: for value in range(a.shape[1]):
>    if value %2 == 1:
>        print a[:,value]

>[ 2  7 12 17]
>[ 4  9 14 19]

I've read something with (: even) but don't know in which way I could use it. Thanks for your Help.

Han

isherwood
  • 58,414
  • 16
  • 114
  • 157
user1339701
  • 321
  • 1
  • 3
  • 3

3 Answers3

92

Let's say you have this array, x:

>>> import numpy
>>> x = numpy.array([[ 1,  2,  3,  4,  5],
... [ 6,  7,  8,  9, 10],
... [11, 12, 13, 14, 15],
... [16, 17, 18, 19, 20]])

To get every other odd row, like you mentioned above:

>>> x[::2]
array([[ 1,  2,  3,  4,  5],
       [11, 12, 13, 14, 15]])

To get every other even column, like you mentioned above:

>>> x[:, 1::2]
array([[ 2,  4],
       [ 7,  9],
       [12, 14],
       [17, 19]])

Then, combining them together yields:

>>> x[::2, 1::2]
array([[ 2,  4],
       [12, 14]])

For more details, see the Indexing docs page.

jterrace
  • 64,866
  • 22
  • 157
  • 202
  • 3
    As numpy arrays are indexed by zero, I believe you are suggesting to get the even rows and odd columns. – lebca Apr 03 '17 at 03:08
  • 3
    This looked like magic so I dug into the docs. Why this works: Numpy indexing follows a start:stop:stride convention. https://numpy.org/doc/stable/user/basics.indexing.html?highlight=indexing#other-indexing-options – gprasant Oct 04 '20 at 23:46
  • 1
    @ErnieSender - see https://numpy.org/doc/stable/user/basics.indexing.html – jterrace Dec 03 '20 at 05:03
  • @ErnieSender As I understand this means *take from index 1 with step 2* (related to cols in this particular case, since stands after `,`), i.e. if you have cols ids as 0,1,2,3,4,5,... it will take 1,3,5,... – RAM237 Dec 25 '20 at 08:26
6

To get every other odd column:

 x[:,0::2]
storaged
  • 1,837
  • 20
  • 34
Taehee Jeong
  • 61
  • 1
  • 2
  • Based on the `start:stop:step` syntax. Changing the `start` can change whether you want odd or even. – Apps 247 Jul 12 '23 at 12:22
2

Slicing an array:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6],[7, 8, 9],[10, 11, 12],[13, 14, 15]])

case1=arr[::2,:]    #odd rows
case2=arr[1::2,:]   #even rows
case3=arr[:,::2]    #odd cols
case4=arr[:,1::2]   #even cols
print(case1)
print("\n") 
print(case2)
print("\n") 
print(case3)
print("\n") 
print(case4)
print("\n")      

Gives:

[[ 1  2  3]
 [ 7  8  9]
 [13 14 15]]


[[ 4  5  6]
 [10 11 12]]


[[ 1  3]
 [ 4  6]
 [ 7  9]
 [10 12]
 [13 15]]


[[ 2]
 [ 5]
 [ 8]
 [11]
 [14]]
Ilja S.
  • 61
  • 3