Indexing and Slicing NumPy Arrays

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

NumPy indexing is used for accessing an element from an array by giving it an index value that starts from 0. Slicing NumPy arrays means extracting elements from an array in a specific range. It obtains a substring, subtuple, or sublist from a string, tuple, or list. There are two types of Indexing: basic and advanced. Advanced indexing is further divided into Boolean and Purely Integer indexing. Negative Slicing index values start from the end of the array.

Introduction

To get some specific data or elements from numpy arrays, NumPy indexing and slicing are used. Indexing starts from 0 and slicing is performed using indexing. 

Indexing an Array

Indexing is used to access individual elements. It is also possible to extract entire rows, columns, or planes from multi-dimensional arrays with numpy indexing. Indexing starts from 0. Let's see an array example below to understand the concept of indexing:

Element of array23119641012
Index01234567

We can perform indexing on arrays in many ways. Let's discuss how indexing is performed on arrays.

Indexing Using Index Arrays

In NumPy arrays, when arrays are used as indexes to access groups of elements, this is called indexing using index arrays. NumPy arrays can be indexed with arrays or with any other sequence like a list, etc.

Let's see some examples to understand how an array can be used as the index for indexing:

Code:

Output:

Explanation: In the above code example, the NumPy array arr is created using the arrange function. The array arr's indices are then stored in another variable arr1 as a new array. Here, we also use negative indexes as negative indexing starts from the last element and the end element is treated as the first element with index -1. Element 9 is at index 4, 1 at index 0, 9 is the last element, so having index -1 and so on. Like this, the elements of the array are indexed.

Indexing in 1 dimension

Code:

Output:

Explanation: In the above code example, an array of shape 4 is created using the np.arange function. The elements at index 0 and 1 of the array are printed as output.

Indexing in 2 Dimensions

Let's look at the example below to understand how numpy indexing is done in a 2-D array:

12(0,0)11(0,1)9 (0,2)
8(1,0)0(1,1)3(1,2)
10(2,0)2(2,1)5(2,2)

Here, the elements have their indexes inside the brackets. Both rows and columns are used for indexing.

Let's look at the example below, where two indexes are given, the first one for the row and the second one for the column.

Code:

Output:

Picking a Row or Column in 2-D NumPy Array

Code:

Output:

Explanation: As discussed above, both rows and columns are used for indexing as two dimensions.

In the above code example, a 2-D array is created using the np.arange function, which is used for creating the 1-D array, and the np.reshape function, which is used for transforming a 1-D array into 2 rows and 4 columns.

Here, 1 in a 2-D array stands for the row at index 1 of an array, i.e., [4 5 6 7]. As a result, the row at index 1 is printed as output.

Indexing in 3 Dimensions

There are three dimensions in a 3-D array, suppose we have three dimensions as (i, j, k), where i stands for the 1st dimension, j stands for the 2nd dimension and, k stands for the 3rd dimension.

Let's look at the given examples for a better understanding. Remember: Indexing starts from zero.

Code:

Output:

Explanation: We want to access the element of an array at index(1,0,2)

Here 1 represents the 1st dimension, and the 1st dimension has two arrays:

1st array: [0,1,2] [3,4,5] and: 2nd array: [6,7,8] [9,10,11]

Indexing starts from 0.

We have the 2nd array as we select 1: [[6,7,8] [9,10,11]

The 2nd digit 0, stands for the 2nd dimension, and the 2nd dimension also contains two arrays: Array 1: [6, 7, 8] and: Array 2: [9, 10, 11]

0 is selected and we have 1st array : [6, 7, 8]

The 3rd digit 2, represents the 3rd dimension, 3rd dimension further has three values: 6,7,8

As 2 is selected, 8 is the output.

Picking a Row or Column in a 3D Array

Code:

Output:

Explanation: We want the row of an array at index(0,1)

Here 0 stands for the 1st dimension, and the 1st dimension has two arrays:

1st array: [0,1,2] [3,4,5] and: 2nd array: [[6,7,8] [9,10,11]

As we select 0, we have 1st array because indexing starts from 0: [0,1,2] [3,4,5]

The 2nd digit 1, stands for the 2nd dimension, and the 2nd dimension also contains two arrays: 1st array: [6, 7, 8] and: 2nd array: [9, 10, 11]

As 1 is selected, we have 2nd array as output: [9, 10, 11]

Picking a matrix in a 3D array

Code:

Output:

Explanation: As we want a matrix of an array at index arr[1]

Here 1 represents the 1st dimension, and the 1st dimension has two arrays:

1st array: [0,1,2] [3,4,5] and: 2nd array: [[6,7,8] [9,10,11]

As indexing starts from 0 and we want matrix at index 1, so 2nd array is selected: [[6,7,8] [9,10,11]

Types of Indexing

There are two types of indexing:

  1. Basic indexing
  2. Advanced indexing

Basic Slicing and indexing

Using basic indexing and slicing we can access a particular element or group of elements from an array.

Basic indexing and slicing return the views of the original arrays.

Basic slicing occurs when the arr[index] is:

  • a slice object (constructed by start: stop: step)
  • an integer
  • or a tuple of slice objects and integers

Code:

Output:

Explanation: In the above example, the first element at index 6 is accessed and then elements are sliced from the 3rd index to the 7th index because the last value is excluded.

Ellipsis can also be used along with basic slicing. An ellipsis is the built-in python constant represented by three dots (...). We can also use "Ellipsis" instead of (...).

Let's see the example below to understand the concept of ellipsis. Code:

Output:

Explanation: There is no such start value mentioned, so all slicing begins from the last dimension, i.e., the 0th column of each row of both layers is selected.

Advanced Indexing

In advanced indexing, we can randomly access elements in an array that are out of order and also are repeatedly.

  • Advanced indexing returns a copy of the data. Advanced indexing is used when the selected object or index:
  • is a non tuple sequence object Like lists or tuples are sequence objects.
  • a ndarray of datatype integer or Boolean
  • or a tuple with at least one sequence object

Let's see an example below of advanced indexing in 2-D arrays.   

In the example given below, the element indexes are (0,0), (1,0), and (2,1), and the matching elements are chosen.

Code:

Output:

Explanation: Inside the print statement, 1st list is for rows and 2nd one is for column indexes at which the element is present. [0,1,2] for 0th row, 1st row, and 2nd row. [0,0,1] for 0th column of 1st row, 0th column of 1st row, and 1st 1st column of 2nd row.

Advanced indexing is of two types:

  1. Purely integer indexing
  2. Boolean indexing

1. Purely Integer Indexing

In this type of indexing, integers are used for numpy indexing.

Indexing using a simple array access by a simple array Code#1:

Output:

Explanation: In the above example, a new array adv_arr of index values is generated. Accessing the elements randomly can also be done repeatedly by using a new array. Like the 1st element of the new array is 1, which is the index of the 2nd element of the original array, arr[adv_arr] becomes arr[1], which is 76. Similarly, it proceeds further.

Code#2:

Output:

Explanation: In the above example elements are indexed using the list of indexes.

2. Boolean Indexing

Boolean indexing occurs when the obj is a Boolean array object, i.e., a true or false type or having some condition.

  • The elements that satisfy the Boolean expression are returned.
  • This is used to filter the values of the desired elements.

Code:

Output:

Explanation: Elements that satisfy the given condition, i.e., greater than 35, are printed as output.

Slicing an Array

Slicing a NumPy array refers to accessing elements from a NumPy array in a specific range using NumPy indexing. It obtains a subtuple, substring, or sublist from a tuple, string, or list.

  • As slicing is performed on Python lists, in the same way, it is performed on NumPy arrays.

The syntax of slicing is as follows:

Syntax: arr_name[start:stop:step] Start: Starting index Stop: Ending index Step: Difference between the index

Let's see how slicing is performed in arrays of different dimensions.

Slicing 1D NumPy Arrays

Code:

Output:

Explanation: As indexing starts from 0, we want elements that start from the 1st index and stop before index 5.

Element of array012345
Index012345

Slicing a 2D Array

In a 2-D array, we have to specify start:stop 2 times. One for the row and 2nd one for the column.

Code:

Output:

Explanation: The 1st number represents the row, so slicing starts from the 1st row and goes till the last as no ending index is mentioned. Then elements from the 1st column to the 3rd column are sliced and printed as output.

Here, rows and columns index are mentioned for better understanding.

Rows ↓, cols →0123
00123
14567
2891011

Slicing a 3D Array

We have to use start:stop:step 3 times. The 1st one is for the planes or layers, 2nd one is for the rows and the last one is for columns.

Let's have a quick look at the example given below:

Code:

Output:

Explanation: we want to slice the array as arr[:2,1:,:2] This selects:

  • As 1st set represents the plane or layer, as no start value is mentioned, slicing begins from the start. So, it selects the first two planes.

A 3-D array contains more than one array in a single array in layers, which are called planes.

Note: the end value is always excluded. Like, if [1:4], this is the case, we start from 1 and go to the 3 indexes.

  • The 2nd set is for rows, rows from index 1 to the last index are sliced as no stopping value is mentioned (the last 2 rows of each selected plane).
  • The third set is for columns, as no starting value is mentioned, slicing begins from the starts and goes to the columns of index 2 (the first 2 columns).

In this case, there are 3 planes mentioned in the above example. Let's take a quick look at planes in the above array.

1st plane:

123
111314
212223

2nd plane:

456
151617
242526

3rd plane:

789
181920
272829

Full Slices

It is used to select all the planes, columns, or rows. Let's look at the examples below:

Code:

Output:

Explanation: [1:3] 1 is for the 2nd row which has index 1. 3 is for columns up to index 3.

Rows ↓, cols →0123
00123
14567
2891011

Code:

Output:

Explanation: [1:,:,:] = This selects from the 2nd plane to the end of the 3-D array because no stopping value is given. There are three planes in the 3-D array: 1st plane:

123
111314
212223

2nd plane:

456
151617
242526

3rd plane:

789
181920
272829

Negative Slicing and Indexing

Negative indexing begins when the array sequence ends, i.e. the last element will be the first element with an index of -1 in negative indexing, and the slicing occurs by using this negative indexing.

Code:

Output:

Slices vs Indexing

Slicing in Python refers to extracting a subset or specific part of the sequence list, tuple, or string in a specific range. While indexing refers to accessing a single element from an array, it is used to get slices of arrays.

Let's see in the following table how slicing is different from indexing in Python.

SlicingIndexing
Accesses a substring or sub-part of an array during slicing and returns a new tuple/listA single item from an array is returned through indexing
Out-of-range indices are handled smoothly when used for slicing.IndexError will be thrown if you try to use an index that is too large.
If a single element is assigned to slicing, it will return TypeError. Only iterables are accepted.We can assign a single assignment or iterable
The length of the list can be changed or even the list can be cleared in slicingThe length of the list cannot be changed by item assignment.

Conclusion

  • Indexing is used for accessing a specific element from an array, and for obtaining a subtuple, substring, or sublist from a tuple, string, or list, slicing is used. By Slicing the NumPy array, we get a specific part of the array.
  • Basic slicing, indexing, and advanced indexing are the types of indexing. Advanced indexing is further divided into Purely integer indexing and Boolean indexing.
  • Negative indexing starts from the end of the array. It starts from a negative index value, i.e. -1.