INDEXING IN NUMPY

In this tutorial, we are going to learn about indexing in Numpy followed by examples of how to fetch elements using indexing in 1D array and 2D arrays.




Once you know how to create an array, you can access the data inside it by using indexing.

Single-Dimensional Indexing

If you want to access data of an array, then all you need to do is enter the index value of the element that you want to retrieve.

import numpy as np arr = np.array([1,2,3,4,5]) arr[4]

You might face an error if you specify the index of an element that is not in the range. For example:

arr[5]

Output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 in 
----> 1 arr[5]
IndexError: index 5 is out of bounds for axis 0 with size 5



Using Negative Indexing

You can apply negative indexing as well if you want to retrieve elements starting from the last of the elements, for example arr[-1] will give you the output of 5.

arr[-1]

Output:

5

Two-Dimensional Indexing

The process of indexing 2D array is similar to indexing the 1D array but with 2D array we have to specify the index position of both row and column of the element. 

two_arr = np.arange(20).reshape(4,5)
two_arr

Output:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Let’s access the element of a 2D array using the index position of row and column

two_arr[0,1]

Output:

1

As you can see that row 0 and column 1 intersects at the element where 1 is stored. This is how you do 2D indexing in Numpy.