How do I extract a sub-array from a numpy 2d array?

Question:

I’d like to extract a numpy array with a specified size from a numpy 2d array–essentially I want to crop the array.
For example, if have a numpy array like this:

([1,2,3],
 [4,5,6],
 [7,8,9])

I’d like to extract a 2×2 from it and the result should be:

([1,2],
 [4,5])

How can I do that?

Asked By: mengmengxyz

||

Answers:

Given this array:

>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

You can slice it along both dimensions:

>>> a[:2,:2]
array([[1, 2],
       [4, 5]])
Answered By: Mike Müller
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.