NumPy Indexing and Slicing

NumPyNumPyBeginner
Practice Now

Introduction

In this lab, we will cover the concepts of Indexing and Slicing in the Numpy Library of Python. We will learn how to access, modify, and extract a range of elements from an array. Different methods of Indexing in the Numpy library will also be explained and demonstrated using examples.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) numpy(("`NumPy`")) -.-> numpy/ArrayBasicsGroup(["`Array Basics`"]) numpy(("`NumPy`")) -.-> numpy/IndexingandSlicingGroup(["`Indexing and Slicing`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") numpy/ArrayBasicsGroup -.-> numpy/multi_array("`Multi-dimensional Array Creation`") numpy/ArrayBasicsGroup -.-> numpy/data_array("`Data to Array`") numpy/IndexingandSlicingGroup -.-> numpy/basic_idx("`Basic Indexing`") numpy/IndexingandSlicingGroup -.-> numpy/bool_idx("`Boolean Indexing`") numpy/IndexingandSlicingGroup -.-> numpy/fancy_idx("`Fancy Indexing`") subgraph Lab Skills python/comments -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} python/lists -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} python/tuples -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} python/importing_modules -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} python/numerical_computing -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} python/build_in_functions -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} numpy/multi_array -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} numpy/data_array -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} numpy/basic_idx -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} numpy/bool_idx -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} numpy/fancy_idx -.-> lab-86452{{"`NumPy Indexing and Slicing`"}} end

Understanding the Basics

  • In NumPy array, slicing is basically the way to extract a range of elements from an array.
  • Items in the ndarray object always follow zero-based index.
  • To access and modify the contents of ndarray object in Numpy Library indexing or slicing can be performed just like the Python's in-built container object.

Numpy Array Slicing

  • Slicing in the array is performed in the same way as it is performed in the python list.
  • If an array has 100 elements and you want to pick only a section of the values, you can perform slicing and extract the required set of values from the complete ndarray.
  • 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:
    • Field access - This is direct field access using the index of the value.
    • Basic Slicing - Basic slicing is simply an extension of Python's basic concept of slicing to the n-dimensions.
    • Advanced Indexing (not covered in this lab)

Examples

  • Let's go through some examples to gain a better understanding of these concepts.

Example 1 - Slicing Ndarray

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 above code prepares an ndarray object using arange() function.
  • 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.

Example 2 - Slicing a Single Item

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 above code slices a single item from the ndarray object.
  • Slicing out a single array can be achieved very easily using indexing.

Example 3

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 above code slices the items starting from a given index till the last index or the last element.

Example 4

import numpy as np

a = np.arange(20)
print("The array is :")
print(a)

print("Slicing of items between two given indexes:")
print(a[2:8])
  • The above code slices all the items between two given indexes.
  • It excludes the value at the ending index.

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.
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:])

Summary

In this lab, we have covered the concept of Indexing and Slicing in Numpy library. We have learned different indexing methods in the Numpy library and various methods of slicing arrays. We have also seen the examples demonstrating the practical implementation of these concepts.

Other NumPy Tutorials you may like