1

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!

1 Answer 1

2

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]

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.