Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get corner values in Python numpy ndarray

Tags:

python

numpy

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.]])
like image 454
user2632453 Avatar asked Jul 30 '13 03:07

user2632453


People also ask

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

Can you slice NumPy arrays?

Slicing in python means extracting data from one given index to another given index, however, NumPy slicing is slightly different. Slicing can be done with the help of (:) . A NumPy array slicing object is constructed by giving start , stop , and step parameters to the built-in slicing function.

What do you get if you apply NumPy SUM () to a list that contains only Boolean values?

sum receives an array of booleans as its argument, it'll sum each element (count True as 1 and False as 0) and return the outcome. for instance np. sum([True, True, False]) will output 2 :) Hope this helps.


3 Answers

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.

like image 163
Jaime Avatar answered Sep 23 '22 07:09

Jaime


How about

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

where A is the array.

like image 35
IanH Avatar answered Sep 24 '22 07:09

IanH


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.]])
like image 21
wwii Avatar answered Sep 20 '22 07:09

wwii