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?
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]])
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?
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]])