How to remove first and last rows and columns from a 2D numpy array?

I would like to know how to remove the first and last rows and columns from a 2D array in numpy. For example, suppose we have a matrix (N+1) x (N+1) called H , then in MATLAB / Octave the code I would use would be:

 Hsub = H(2:N,2:N); 

What is the equivalent code in Numpy? I thought np.reshape could do what I want, but I'm not sure how to make it delete only the target rows, as I think if I go to the matrix (N-1) x (N-1) , it will delete the last two rows and columns.

+6
source share
1 answer

How about this?

 Hsub = H[1:-1, 1:-1] 

A range of 1:-1 means that we are accessing the elements from the second index or 1 , and we are approaching the second last index, as indicated by -1 for the measurement. We do this for both dimensions independently. When you do this yourself for both dimensions, the result is the intersection of how you access each dimension, which essentially interrupts the first row, first column, last row, and last column.

Remember that the final index is exclusive , so if we did 0:3 , we would get only the first three elements of the dimension, not four.

In addition, negative indices mean that we are accessing an array with end . -1 is the last value to access in a particular dimension, but due to exclusivity we get the second element, not the last element. Essentially, this is the same as doing:

 Hsub = H[1:H.shape[0]-1, 1:H.shape[1]-1] 

... but using negative indexes is much more elegant. You also should not use the number of rows and columns to extract from them what you need. The above syntax is agnostic. However, you need to make sure that the matrix is ​​at least 3 x 3, or you get an error message.

Little bonus

In MATLAB / Octave, you can achieve the same without using dimensions:

 Hsub = H(2:end-1, 2:end-1); 

The end keyword with respect to indexing means getting the last element for a particular dimension.

Usage example

Here is an example (using IPython):

 In [1]: import numpy as np In [2]: H = np.meshgrid(np.arange(5), np.arange(5))[0] In [3]: H Out[3]: array([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) In [4]: Hsub = H[1:-1,1:-1] In [5]: Hsub Out[5]: array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) 

As you can see, the first row, the first column, the last row and the last column were removed from the original matrix H , and the rest was placed in the output matrix Hsub .

+9
source

Source: https://habr.com/ru/post/984068/


All Articles