× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How do I remove the first and last rows and columns from a 2D numpy array?

Ray Phan
Mar 24, 2015
<p>How about this?</p> <pre><code>Hsub = H[1:-1, 1:-1] </code></pre> <p>The <code>1:-1</code> range means that we access elements from the second index, or <code>1</code>, and we go up to the second last index, as indicated by the <code>-1</code> for a dimension. We do this for both dimensions independently. When you do this independently for both dimensions, the result is the intersection of how you're accessing each dimension, which is essentially chopping off the first row, first column, last row and last column.</p> <p>Remember, the ending index is <strong>exclusive</strong>, so if we did <code>0:3</code> for example, we only get the first <strong>three</strong> elements of a dimension, not four. </p> <p>Also, negative indices mean that we access the array from the <strong>end</strong>. <code>-1</code> is the last value to access in a particular dimension, but because of the exclusivity, we are getting up to the second last element, not the last element. Essentially, this is the same as doing:</p> <pre><code>Hsub = H[1:H.shape[0]-1, 1:H.shape[1]-1] </code></pre> <p>... but using negative indices is much more elegant. You also don't have to use the number of rows and columns to extract out what you need. The above syntax is dimension agnostic. However, you need to make sure that the matrix is at least 3 x 3, or you'll get an error. </p> <h1>Small bonus</h1> <p>In MATLAB / Octave, you can achieve the same thing without using the dimensions by:</p> <pre><code>Hsub = H(2:end-1, 2:end-1); </code></pre> <p>The <code>end</code> keyword with regards to indexing means to get the last element for a particular dimension.</p> <h1>Example use</h1> <p>Here's an example (using IPython):</p> <pre><code>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]]) </code></pre> <p>As you can see, the first row, first column, last row and last column have been removed from the source matrix <code>H</code> and the remainder has been placed in the output matrix <code>Hsub</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29176339/How%20do%20I%20remove%20the%20first%20and%20last%20rows%20and%20columns%20from%20a%202D%20numpy%20array?/29176381">Stack Overflow</a>.</p>
comments powered by Disqus