NumPy indexing and slicing

Array indices in NumPy start at 0 as in languages such as Python, Java, and C++ and unlike in Fortran, Matlab, and Octave, which start at 1. Arrays can be indexed in the standard way as we would index into any other Python sequences:

    # print entire array, element 0, element 1, last element.
    In [36]: ar = np.arange(5); print ar; ar[0], ar[1], ar[-1]
    [0 1 2 3 4]
    Out[36]: (0, 1, 4)
    # 2nd, last and 1st elements
    In [65]: ar=np.arange(5); ar[1], ar[-1], ar[0]
    Out[65]: (1, 4, 0)

Arrays can be reversed using the ::-1 idiom as follows:

    In [24]: ar=np.arange(5); ar[::-1]
    Out[24]: array([4, 3, 2, 1, 0])

Multidimensional arrays are indexed using tuples of integers:

    In [71]: ar = np.array([[2,3,4],[9,8,7],[11,12,13]]); ar
    Out[71]: array([[ 2,  3,  4],
                    [ 9,  8,  7],
                    [11, 12, 13]])
    In [72]: ar[1,1]
    Out[72]: 8

Here, we set the entry at row1 and column1 to 5:

    In [75]: ar[1,1]=5; ar
    Out[75]: array([[ 2,  3,  4],
                    [ 9,  5,  7],
                    [11, 12, 13]])

Retrieve row 2:

    In [76]:  ar[2]
    Out[76]: array([11, 12, 13])
    In [77]: ar[2,:]
    Out[77]: array([11, 12, 13])
  

Retrieve column 1:

    In [78]: ar[:,1]
    Out[78]: array([ 3,  5, 12])
  

If an index is specified that is out of bounds of the range of an array, IndexError will be raised:

    In [6]: ar = np.array([0,1,2])
    In [7]: ar[5]
       ---------------------------------------------------------------------------
       IndexError                  Traceback (most recent call last)
      <ipython-input-7-8ef7e0800b7a> in <module>()
       ----> 1 ar[5]
          IndexError: index 5 is out of bounds for axis 0 with size 3
  

Thus, for 2D arrays, the first dimension denotes rows and the second dimension, the columns. The colon (:) denotes selection across all elements of the dimension.

..................Content has been hidden....................

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