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: Digital Sunset Looping
--
Chapters
00:00 Select &Quot;Corner&Quot; Elements Of A 2d Numpy Array
00:46 Accepted Answer Score 5
00:56 Answer 2 Score 3
01:34 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: Digital Sunset Looping
--
Chapters
00:00 Select &Quot;Corner&Quot; Elements Of A 2d Numpy Array
00:46 Accepted Answer Score 5
00:56 Answer 2 Score 3
01:34 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.