Select "corner" elements of a 2D NumPy array
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Select &Quot;Corner&Quot; Elements Of A 2d Numpy Array
00:50 Accepted Answer Score 5
01:04 Answer 2 Score 3
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/4906...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #numpy #indexing
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Select &Quot;Corner&Quot; Elements Of A 2d Numpy Array
00:50 Accepted Answer Score 5
01:04 Answer 2 Score 3
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/4906...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #numpy #indexing
#avk47
ACCEPTED ANSWER
Score 5
You can do:
data[[0, 0, -1, -1], [0, -1, 0, -1]]
ANSWER 2
Score 3
Here are two possibilities. (Ok, first one isn't actually fancy):
>>> a = np.arange(9).reshape(3, 3)
>>>
>>> m, n = a.shape
>>> a[::m-1, ::n-1]
array([[0, 2],
[6, 8]])
>>>
>>> a[np.ix_((0,-1), (0,-1))]
array([[0, 2],
[6, 8]])
More explicitly:
>>> idx = np.ix_((0,-1), (0,-1))
>>> idx
(array([[ 0],
[-1]]), array([[ 0, -1]]))
>>> a[idx]
array([[0, 2],
[6, 8]])
The trick is to leverage broadcasting on the indices. np.ix_ knows the details of how to do it.