6
votes

I'm trying to access the corner values of a numpy ndarray. I'm absolutely stumped as for methodology. Any help would be greatly appreciated.

For example, from the below array I'd like a return value of array([1,0,0,5]) or array([[1,0],[0,5]]).

array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  5.],
       [ 0.,  0.,  5.,  5.]])
4

4 Answers

8
votes

To add variety to the answers, you can get a view (not a copy) of the corner items doing:

corners = a[::a.shape[0]-1, ::a.shape[1]-1]

Or, for a generic n-dimensional array:

corners = a[tuple(slice(None, None, j-1) for j in a.shape)]

Doing this, you can modify the original array by modifying the view:

>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> corners = a[tuple(slice(None, None, j-1) for j in a.shape)]
>>> corners
array([[0, 2],
       [6, 8]])
>>> corners += 1
>>> a
array([[1, 1, 3],
       [3, 4, 5],
       [7, 7, 9]])

EDIT Ah, you want a flat list of corner values... That cannot in general be achieved with a view, so @IanH's answer is what you are looking for.

6
votes

How about

A[[0,0,-1,-1],[0,-1,0,-1]]

where A is the array.

2
votes

Use np.ix_ to construct the indices.

>>> a
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 5.],
       [0., 0., 5., 5.]])

>>> corners = np.ix_((0,-1),(0,-1))

>>> a[corners]
array([[1., 0.],
      [0., 5.]])
0
votes

You can manually specify the corners (using negative indexes):

a = numpy.array([[ 1.,  0.,  0.,  0.],
  [ 0.,  1.,  0.,  0.],
  [ 0.,  0.,  1.,  5.],
  [ 0.,  0.,  5.,  5.]])

result = numpy.array([a[0][0],a[0][-1],a[-1][0],a[-1][-1]])
# result will contain array([ 1.,  0.,  0.,  5.])

result = numpy.array([a[0][0],a[0][-1],a[-1][0],a[-1][-1]])
# result will contain array([[ 1.,  0.],
#                            [ 0.,  5.]])