Reputation: 899
So say I have this 2d numpy array:
(
[
[1,2,3,4],
[5,6,7,8],
[9,8,7,6],
[5,4,3,2]
]
);
I'd like to sub-sample this and get 2 by 2 like this (indexing every other row and every other column):
(
[
[1,3],
[9,7]
]
)
Is there a way to do this without any loops?
Thank you!
Upvotes: 1
Views: 408
Reputation: 152657
Yes you can use indexing with steps (in your example step would be 2):
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,8,7,6], [5,4,3,2]])
a[::2, ::2]
returns
array([[1, 3],
[9, 7]])
The syntax here is [dim1_start:dim1_stop:dim1_step, dim2_start:dim2_stop:dim2_step]
Upvotes: 2