Array slicing

Arrays can be sliced using the syntax ar[startIndex: endIndex: stepValue]:

    In [82]: ar=2*np.arange(6); ar
    Out[82]: array([ 0,  2,  4,  6,  8, 10])
    In [85]: ar[1:5:2]
    Out[85]: array([2, 6])

Note that if we wish to include the endIndex value, we need to go above it, as follows:

    In [86]: ar[1:6:2]
    Out[86]: array([ 2,  6, 10])  

Obtain the first nelements using ar[:n]:

    In [91]: ar[:4]
    Out[91]: array([0, 2, 4, 6])  

The implicit assumption here is that startIndex=0, step=1.

Start at element 4 and select all the elements till the end:

    In [92]: ar[4:]
    Out[92]: array([ 8, 10])  

Slice array with stepValue=3:

    In [94]: ar[::3]
    Out[94]: array([0, 6]) 

To illustrate the scope of indexing in NumPy, let's refer to the following diagram, which is taken from a NumPy lecture given at SciPy 2013 and can be found at http://scipy-lectures.github.io/_images/numpy_indexing.png:

Pictorial illustration of NumPy indexing

Let's now examine the meanings of the expressions in the preceding diagram:

  • The expression a[0,3:5] indicates the start at row 0, columns 3-5, column 5 not included.
  • In the expression a[4:,4:], the first 4 indicates the start at row 4 and will give all columns, that is, the array [[40, 41,42,43,44,45] [50,51,52,53,54,55]]. The second 4 shows the cutoff at the start of column 4 to produce the array [[44, 45], [54, 55]].
  • The expression a[:,2] gives all rows from column 2.
  • Now, in the last expression, a[2::2,::2], 2::2 indicates that the start is at row 2 and the step value here is also 2. This would give us the array [[20, 21, 22, 23, 24, 25], [40, 41, 42, 43, 44, 45]]. Further, ::2 specifies that we retrieve columns in steps of 2, producing the end result array ([[20, 22, 24], [40, 42, 44]]).

Assignment and slicing can be combined as shown in the following code snippet:

    In [96]: ar
    Out[96]: array([ 0,  2,  4,  6,  8, 10])
    In [100]: ar[:3]=1; ar
    Out[100]: array([ 1,  1,  1,  6,  8, 10])
    In [110]: ar[2:]=np.ones(4);ar
    Out[110]: array([1, 1, 1, 1, 1, 1])
  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset