Open In App

Basic Slicing and Advanced Indexing in NumPy

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Indexing a NumPy array means accessing the elements of the NumPy array at the given index.

There are two types of indexing in NumPy: basic indexing and advanced indexing.

Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data.

In this tutorial, we will cover basic slicing and advanced indexing in the NumPy. NumPy arrays are optimized for indexing and slicing operations making them a better choice for data analysis projects.

Prerequisites 

Numpy in Python Introduction

Indexing an NumPy Array

Indexing is used to extract individual elements from a one-dimensional array.

It can also be used to extract rows, columns, or planes in a multi-dimensional NumPy array.

Example: Index in NumPy array

Element 23 21 55 65 23
Index 0 1 2 3 4

In the above example, we have highlighted the element “55” which is at index “2”.

Let’s discuss different methods to perform indexing in the NumPy array:

Indexing Using Index arrays

Indexing can be done in NumPy by using an array as an index.

Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on.

In the case of slicing, a view or shallow copy of the array is returned but in an index array, a copy of the original array is returned.

Example: Indexing using an index array

Python




import numpy as np
# Create a sequence of integers from 10 to 1 with a step of -2
a = np.arange(10, 1, -2
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the np.array method.
newarr = a[np.array([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)


Output : 

A sequential array with a negative step:
[10 8 6 4 2]
Elements at these indices are:
[4 8 6]

Types of Indexing in NumPy Array

There are two types of indexing used in Python NumPy:

  • Basic slicing and indexing
  • Advanced indexing
    • Purely integer indexing
    • Boolean indexing

Basic Slicing and indexing

Basic slicing and indexing is used to access a specific element or range of elements from a NumPy array.

Basic slicing and indexing only return the view of the array.

Consider the syntax x[obj] where “x” is the array and “obj” is the index. The slice object is the index in the case of basic slicing.

Basic slicing occurs when obj is :

  1. A slice object that is of the form start: stop: step
  2. An integer
  3. Or a tuple of slice objects and integers

All arrays generated by basic slicing are always ‘view’ of the original array.

Example: Basic Slicing in NumPy array

Python




import numpy as np 
# Arrange elements from 0 to 19 
a = np.arrange(20
print("\n Array is:\n ",a) 
print("\n a[15]=",a[15])
# a[start:stop:step]
print("\n a[-8:17:1] = ",a[-8:17:1]) 
print("\n a[10:] = ",a[10:])


Output :

Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[15]= 15
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]

Ellipsis can also be used along with basic slicing. Ellipsis (…) is the number of: objects needed to make a selection tuple of the same length as the dimensions of the array.

Example: Basic slicing with ellipses

Python




import numpy as np 
# A 3 dimensional array. 
b = np.array([[[1, 2, 3],[4, 5, 6]], 
            [[7, 8, 9],[10, 11, 12]]]) 
print(b[...,1]) #Equivalent to b[: ,: ,1 ]


Output :

[[ 2  5]
[ 8 11]]

Advanced indexing

NumPy Advanced indexing returns a copy of data rather than a view of it. Advanced indexing is of two types integer and Boolean.

Advanced indexing in the NumPy array allows you to access and manipulate complex patterns of the data.

Advanced indexing is triggered when obj is : 

  • an ndarray of type integer or Boolean
  • or a tuple with at least one sequence object
  • is a non tuple sequence object

Types of Advanced Indexing

There are two types of Advanced Indexing in NumPy array indexing:

  • Purely integer indexing
  • Boolean integer indexing

Purely integer array indexing

Purely integer array indexing allows us to access elements from an ndarray (N-dimensional array) using integers.

When integers are used for indexing. Each element of the first dimension is paired with the element of the second dimension. So the index of the elements in this case are (0,0),(1,0),(2,1) and the corresponding elements are selected.

Example: Using purely integer array indexing

Python




# Python program showing advanced indexing
import numpy as np
a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])
print(a[[0 ,1 ,2 ],[0 ,0 ,1]])


Output : 

[1 3 6]

Boolean Indexing 

This indexing has some boolean expressions as the index.

Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values.

Example 1: Using boolean indexing on NumPy array to find numbers greater than 50

Python




# You may wish to select numbers greater than 50
import numpy as np
  
a = np.array([10, 40, 80, 50, 100])
print(a[a>50])


Output : 

[80 100]

Example 2: Using boolean indexing on NumPy array to find numbers whose sum row is 10

Python




# You may wish to select those elements whose
# sum of row is a multiple of 10.
import numpy as np
  
b = np.array([[5, 5],[4, 5],[16, 4]])
sumrow = b.sum(-1)
print(b[sumrow%10==0])


Output : 

array([[ 5, 5], [16, 4]])

Conclusion

Indexing and Slicing are very important concepts for accessing data. Python NumPy allows you very easy methods for indexing and slicing elements from a NumPy array.

In this tutorial, we have basic slicing and advanced indexing in NumPy Python. We have explained basic slicing with examples and also dived deep into Advanced indexing. We have covered types of advanced indexing and explained each type in easy words with examples.

After completing this tutorial you will be easily able to apply index and slicing operations on your NumPy ndarrays. This tutorial will help you to save time and gain more skills.



Last Updated : 08 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads