Array indexing in NumPy refers to the method of accessing specific elements or subsets of data within an array. This feature allows us to retrieve, modify and manipulate data at specific positions or ranges helps in making it easier to work with large datasets.
In this article, we’ll see the different ways to index and slice NumPy arrays which helps us to work with our data more effectively.
Accessing Elements
In NumPy, every element inside an array is located using indices.
- In 1D arrays, we use a single index -> arr[index]
- In 2D arrays, we use row and column indices -> arr[row, column]
- In 3D arrays, we use depth, row, and column -> arr[depth, row, column]
Indices start from 0, and NumPy also supports negative indexing (like -1 for the last element). Now let’s see with examples how to access elements in different types of arrays.
Example 1: This example creates a 1D array and accesses the element at index 0.
Python
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0])
Explanation: arr[0] accesses the first element because index 0 refers to the first position in the array.
Example 2: This example accesses a value by specifying its row and column index in a 2D array.
Python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[1, 2])
Explanation: arr[1, 2] accesses the element in the second row (index 1) and third column (index 2) which is 6.
Example 3: This example accesses a value using depth, row, and column indices in a 3D array.
Python
import numpy as np
arr = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])
print(arr[1, 2, 0])
Explanation: arr[1, 2, 0] selects the value at - depth index 1 -> second 2D layer, row index 2 -> third row and column index 0 -> first column and the accessed value is 16.
Slicing Arrays
Slicing in NumPy lets us extract a specific portion of an array using the format start:stop:step. This works for both 1D and multidimensional arrays, allowing us to easily select ranges of values or smaller sub-arrays.
Example 1: This example slices a continuous range of values from a 1D array using start:stop.
Python
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5])
print(arr[1:4])
Explanation: arr[1:4] extracts elements from index 1 to 3 (stop index 4 is excluded).
Example 2: This example selects a submatrix by applying slicing to rows and columns separately in a 2D Array.
Python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[0:2, 1:3])
Explanation: arr[0:2] selects rows at indices 0 and 1, arr[:, 1:3] selects columns at indices 1 and 2 and together forms the submatrix [[2 3], [5 6]]
Example 3: This example extracts part of a 3D array by slicing depth, rows, and columns.
Python
import numpy as np
arr = np.array([
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
])
print(arr[1:2, 0:2, 1:3])
Output[[[11 12]
[14 15]]]
Explanation: arr[1:2] selects the second 2D slice (depth index 1), 0:2 selects first two rows, 1:3 selects columns at index 1 and 2 and result in the sliced 3D block [[[11 12], [14 15]]]
Boolean Indexing
It allows us to filter elements from an array based on a condition and returns only those that meet it. We create a boolean array from a condition and use it to select elements and can combine conditions with logical operators.
Python
import numpy as np
arr = np.array([10, 15, 20, 25, 30])
print(arr[arr > 20])
Explanation: arr > 20 returns True for elements greater than 20 so only 25 and 30 are selected and printed.
We can also use logical operators like & (AND), | (OR) and ~ (NOT) to combine conditions.
Python
import numpy as np
arr = np.array([10, 15, 20, 25, 30])
print(arr[(arr > 10) & (arr < 30)])
Explanation: arr[(arr > 10) & (arr < 30)] selects elements greater than 10 and less than 30 resulting in [15, 20, 25].
Fancy Indexing
It is also known as Advanced Indexing which allows us access elements of an array by using another array or list of indices. This allows selecting multiple elements at once even if they are not next to each other which makes it easy to pick specific values from different positions in the array.
Python
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
idx = [0, 2, 4]
print(arr[idx])
Explanation: It uses the list [0, 2, 4] to pick elements at those specific positions which returns [10, 30, 50].
Integer Array Indexing
It is similar to fancy indexing and uses an array of integers to select multiple elements from another array. This method allows us to access elements at specific, non-adjacent positions which makes it useful for extracting scattered data points.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[[0, 2, 4]])
Explanation: Using an integer array [0, 2, 4] which selects the elements at those indices and returns [1, 3, 5].
Ellipsis (...) in Indexing
The ellipsis (...) can be used to select all dimensions which are not explicitly mentioned. This is helpful in multidimensional arrays when we don’t want to specify every dimension.
Python
import numpy as np
arr = np.random.rand(4, 4, 4)
print(arr[..., 0])
Output[[0.83640721 0.50678908 0.30762677 0.86968762]
[0.70001868 0.09882074 0.20541691 0.32463232]
[0.77609753 0.90449254 0.12313748 0.0147615 ]
[0.95180053 0.41046122 0.26144879 0.33313565]]
Explanation: arr[..., 0] selects all elements in the first two dimensions and 0 selects the first element along the last dimension for each.
Note: It will generate random number as it uses random function.
Using np.newaxis to Add New Dimensions
The np.newaxis keyword adds a new axis to the array which helps in converting a 1D array into a row or column vector.
Python
import numpy as np
arr = np.array([1, 2, 3])
print(arr[:, np.newaxis])
Explanation: arr[:, np.newaxis] adds a new axis helps in converting the 1D array into a 2D column vector with shape (3,1).
Modifying Array Elements
We can modify array elements directly by using indexing or slicing. This makes it easy to update specific elements or ranges of elements in an array.
Python
import numpy as np
arr = np.array([1, 2, 3, 4])
arr[1:3] = 99
print(arr)
Explanation: arr[1:3] selects elements at indices 1 and 2 and replaces them with 99.
Which method returns the number of dimensions of an array?
Explanation:
.ndim shows how many dimensions the array has (1D, 2D, etc.).
What is the output of arr[0] if arr = np.array([10, 20, 30])?
Explanation:
Indexing starts at 0 so arr[0] gives the first element.
In a 2D array what does arr[1][0] give?
-
First element of second row
-
Second element of second row
-
First element of first row
-
Explanation:
The first index selects the row the second selects the element in that row.
Quiz Completed Successfully
Your Score : 2/3
Accuracy : 0%
Login to View Explanation
1/3
1/3
< Previous
Next >
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice