Python NumPy - Indexing and Slicing Arrays

Just like lists, individual elements and slices of arrays can be selected using bracket notation. Unlike lists, however, arrays also permit selection using other arrays. That is, we can use array selectors to filter for specific subsets of elements of other arrays.

First, let's look at some examples of one-dimensional arrays that behave just like lists. Let's create an array called myarray with 10 values.

>>> import numpy as np
>>> myarray = np.arange(10)
>>> myarray
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>

As you can see, for arrays, indexing starts with 0. We have a few examples of selecting values below. In the first example, we select a single value at index 5 (6th value in the array). In the second example, we select all the elements of the array starting with index 2. In the third example,we specify the index range as 2 to 6. This will select all elements starting from index 2 upto but not including index 6. In the last example, we select all values except the last (-1).

>>> myarray[5]
5
>>> myarray[2:]
array([2, 3, 4, 5, 6, 7, 8, 9])
>>> myarray[2:6]
array([2, 3, 4, 5])
>>> myarray[:-1]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>>

Slicing is possible over all dimensions. Let's look at some examples of slicing in a two-dimensional array. Let's say we have the following 2-d array:

>>> array2d = np.array([[10,20,30],[40,50,60]])
>>> array2d
array([[10, 20, 30],
       [40, 50, 60]])
>>>

Following are a few examples of slicing this array:

>>> array2d[1,1]
50
>>> array2d[0,2]
30
>>>

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads