Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects.
NumPy Indexing
NumPy Indexing is used to access or modify elements in an array. Three types of indexing methods are available: field access, basic slicing, and advanced indexing.
Example 1
In the below example, we have created an array using the arange() function, and let us see how to access a single element from the array i.e, 6.
Following is an output of the above code:
Example 2
Let's say we have a list which contains 5 student marks in English and we need to access the score of the third student. We use arr[2] as the index starts from '0'.
Following is an output of the above code:
Slicing in NumPy
NumPy Slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array.
Example 1
In the below code we will see how to access the last two elements from the array using arr[-2:]. As we didn't specify the stop parameter, it accesses the elements from the second last to the end of the array.
Following is an output of the above code:
Example 2
Let's say we have an array containing numbers 1 to 12 and need to access only even numbers. We use slicing with step parameter arr[::2] as it slices every second element in the array.
Following is an output of the above code:
Example 3
Let's create a 2D array and use slicing to access the second column in the array. To access all rows (:) but only the second column (index 1), we use arr[:, 1].
Following is an output of the above code:
Example 4
In the below code we have created a 2D array and let us see how to access all elements from row 2 (index 1) — we use a[1:]. Where, a[1:] selects all rows starting from the second row (index 1) to the last, including all columns.
Following is an output of the above code:
Example 5
Let us see how to slice an array between indexes.
When we run above program, it produces following result:
Advanced Indexing
Advanced indexing offers a robust method to select specific elements from a NumPy array based on predetermined conditions or guidelines.
array[1:4] gives you a "view" of the original array (where modifications to the slice affect the original data), advanced indexing always creates a copy of the selected data.
It allows you to select elements from an ndarray that is a non-tuple sequence, ndarray object of integer or Boolean data type, or a tuple with at least one item being a sequence object. This method is helpful in dynamic data selection as well as conditional data extraction.
There are two types of advanced indexing:
- Integer Indexing
- Boolean Array Indexing
Integer Indexing
This allows you to select specific elements from an array using their exact positions (indices) based on its N-dimensional index. Each integer array represents the number of indexes into that dimension.
If the number of integer arrays corresponds to the dimensions of the target ndarray, selecting items becomes simple and straightforward. It's like selecting an item at x, y, z position.
Example: Selecting Elements by Indices
The following example selects one element from each row of the array using integer arrays for both rows and columns. The selection includes elements at (0,0), (1,1) and (2,0) from the first array.
Following is the output of the above code:
Example: Selecting Corner Elements
In the following example, elements placed at corners of a 4X3 array are selected. The row indices of selection are [0, 0] and [3,3] whereas the column indices are [0,2] and [0,2].
Following is the output of the above code:
Example: Accessing Specific Marks
In this example we have a 2D array which contains marks of three different students representing in rows and marks in three columns of different subjects Hindi, Maths, English. Now, we will see how to access a score of student 1 in Hindi and score of student 2 in Maths.
Output of the above code is as follows:
Example: Index Out of Bounds Error
In NumPy an index error (index out of bounds) occurs when you try to access an element in the array using the index that is outside the valid range of array dimensions. Let us understand this with an example where an array contains 3 rows but the code attempts to access the 4th row (index 3), throwing an index error.
Following is the output of the above code:
Boolean Array Indexing
NumPy's Boolean indexing lets you select array elements that meet a certain condition. It involves creating a Boolean array where each element matches up with a True or False condition. The elements from the original array are selected where the Boolean array shows True.
This approach works well to filter data using logical conditions, like comparison operations. It is a powerful tool to pull out specific values from arrays.
Example: Using a Boolean Array to Select Specific Elements
This code illustrates how to use a Boolean array as a mask for selecting certain elements from a NumPy array. The Boolean array specifies which elements are to be included (True) or excluded (False) in the final array.
Output of the above code is as follows:
Example: Filtering Items Greater Than 5
In this example, items greater than 5 are returned as a result of Boolean indexing.
When we run above program, it produces following result:
Example: Removing NaN Values
In this example, NaN (Not a Number) elements are omitted by using ~ (complement operator).
When we run above program, it produces following result:
Example: Filtering Complex Numbers
The following example shows how to filter out the complex numbers from an array.
Output of the above code is as follows:
Example: Extracting Even Numbers
Let us see how to extract even numbers from an array using boolean indexing:
Following is the output of the above code: