Signup/Sign In

Python NumPy Indexing and Slicing

In this tutorial, we will cover Indexing and Slicing in the Numpy Library of Python.

To access and modify the contents of ndarray object in Numpy Library indexing or slicing can be done just like the Python's in-built container object.

We had also mentioned in our previous tutorials, that items in the ndarray object always follow zero-based index.

Numpy Array Slicing:

In NumPy array, Slicing is basically the way to extract a range of elements from an array. In NumPy, slicing in the array is performed in the same way as it is performed in the python list.

In simpler words, if you have an array of say 100 elements, and you want to pick only a section of the values, then we can perform slicing and get the required set of values from the complete ndarray. In the examples below, you will see code examples for slicing.

Learn Python List Slicing and you can apply the same on Numpy ndarrays.

Numpy Array Indexing:

There are three types of Indexing methods that are available in Numpy library and these are given below:

  • Field access - This is direct field access using the index of the value, for example, [0] index is for 1st value, [1] index is for the 2nd value, and so on.

  • Basic Slicing - Basic slicing is simply an extension of Python's basic concept of slicing to the n dimensions. In order to construct a Python slice object you just need to pass the start, stop, and step parameters to the built-in slice function. Further, this slice object is passed to the array to extract the part of the array.

  • Advanced Indexing (covered on the next page)

Let us cover some examples in order to gain an understanding of these concepts.

Example 1: Slicing ndarray

In the code example given below, we will prepare an ndarray object using arange() function. Then we will define a slice object is defined with start, stop, and step values 2, 7, and 2 respectively. After that this slice object is passed to the ndarray, a part of it that is starting with index 2 up to 7 with a step value of 2 will be sliced. By step value, we mean that from 2 to 7, starting from 2, every third element will be picked, after 2 we jump 3, and include 4, then jump 5, and include 6.

You can also obtain the same result just by giving the slicing parameters separated by a colon : like (start: stop: step) directly to the ndarray object.

import numpy as np 

a = np.arange(10) 
print("The ndarray is :")
print(a)

s = slice(2,7,2) 
print("After applying slice() Function:")
print (a[s])


The ndarray is :
[0 1 2 3 4 5 6 7 8 9]
After applying slice() Function:
[2 4 6]

Example 2: Slicing a single item

In the code example given below we will slice a single item from the ndarray object. Slicing out a single array can be achieved very easily using indexing.

import numpy as np 

a = np.arange(15)
print("The array is :")
print(a)
# using the index directly
b = a[7] 
print("The Eighth item in the array is :")
print (b)


The array is :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
The Eighth item in the array is :
7

Example 3:

In the example given below, we will slice the items starting from a given index till the last index or the last element:

import numpy as np
 
a = np.arange(20) 
print("The array is :");
print(a)

print("Slicing of items starting from the index:")
print (a[2:])


The array is :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Slicing of items starting from the index:
[ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

Example 4:

In the example given below, we will slice all the items between two given indexes:

import numpy as np
 
a = np.arange(20) 
print("The array is :");
print(a)

print("Slicing of items starting from the index:")
print (a[2:8])


The array is :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Slicing of items starting from the index:
[2 3 4 5 6 7]

NOTE: From the above output, it is clear that it will exclude the value at the ending index.

Example 5: Using Ellipsis

While slicing, ellipsis () is used to make a selection tuple of the same length as the dimension of an array. For a multidimensional ndarray, if the ellipsis is used at the row position, it will return an ndarray comprising of items in rows and similarly for the columns.

Below we have an example where we will use ellipsis:

import numpy as np 
a = np.array([[11,2,23],[33,44,5],[84,25,16]]) 

print ("The array is :") 
print (a )
print ('\n')

#To return array of items in the second column 
print ('The items in the second column are:')  
print (a[..., 1] )
print ('\n')

# In order to slice all items from the second row 
print ('The items in the second row are:') 
print (a[1, ...])
print ('\n') 

# In order to slice all items from column 1 onwards 
print ('The items onwards to column 1 are:' )
print (a[..., 1:])


The array is :
[[11 2 23]
[33 44 5]
[84 25 16]]


The items in the second column are:
[ 2 44 25]


The items in the second row are:
[33 44 5]


The items onwards to column 1 are:
[[ 2 23]
[44 5]
[25 16]]

Summary

In this tutorial, we have covered the concept of Indexing and Slicing in Numpy library, different indexing methods in the Numpy library. Then with the help of examples, we have covered different use cases.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.