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.

import numpy as np a = np.arange(10) b = a[6] print(b)

Following is an output of the above code:

6

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'.

import numpy as np scores = ['86', '98', '100', '65', '75'] arr = np.array(scores) print("Third student score is:", arr[2])

Following is an output of the above code:

Third student score is: 100

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.

import numpy as np arr = np.arange(6) print(arr[-2:])

Following is an output of the above code:

[4 5]

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.

import numpy as np arr = np.arange(12) even_num = arr[::2] print("Even Numbers:", even_num)

Following is an output of the above code:

Even Numbers: [ 0 2 4 6 8 10]

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

import numpy as np arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print(arr[:, 1])

Following is an output of the above code:

[20 50 80]

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.

import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print(a) # slice items starting from index print('Now we will slice the array from the index a[1:]') print(a[1:])

Following is an output of the above code:

[[1 2 3] [3 4 5] [4 5 6]] Now we will slice the array from the index a[1:] [[3 4 5] [4 5 6]]

Example 5

Let us see how to slice an array between indexes.

import numpy as np a = np.arange(10) print("Array from index 1 to 6:", a[1:7])

When we run above program, it produces following result:

Array from index 1 to 6: [1 2 3 4 5 6]

Advanced Indexing

Advanced indexing offers a robust method to select specific elements from a NumPy array based on predetermined conditions or guidelines.

View vs Copy: While basic indexing, like 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.

import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) y = x[[0,1,2], [0,1,0]] print(x) print('The new array is :\n', y)

Following is the output of the above code:

[[1 2] [3 4] [5 6]] The new array is : [1 4 5]

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

import numpy as np x = np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) print('Our array is: \n', x) rows = np.array([[0,0], [3,3]]) cols = np.array([[0,2], [0,2]]) y = x[rows,cols] print('The corner elements of this array are: \n', y)

Following is the output of the above code:

Our array is: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] The corner elements of this array are: [[ 0 2] [ 9 11]]

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.

import numpy as np marks = np.array([[85, 99, 88], [78, 93, 85], [86, 45, 90]]) specific_results = marks[[0, 1], [0, 1]] print('Marks:\n', marks) print('Selected marks: \n', specific_results)

Output of the above code is as follows:

Marks: [[85 99 88] [78 93 85] [86 45 90]] Selected marks: [85 93]

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.

import numpy as np x = np.array([[0, 1], [2, 3], [4, 65]]) print('The 2D array is : \n', x) print(x[3,1])

Following is the output of the above code:

The 2D arrays is : [[ 0 1] [ 2 3] [ 4 65]] Traceback (most recent call last): File "main.py", line 4, in <module> print(x[3,1]) IndexError: index 3 is out of bounds for axis 0 with size 3

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.

import numpy as np arr = np.array([10, 20, 30, 40, 50]) bool_array = np.array([True, False, True, False, True]) selected_elements = arr[bool_array] print("Original array:", arr) print("Boolean array:", bool_array) print("Selected elements:", selected_elements)

Output of the above code is as follows:

Original array: [10 20 30 40 50] Boolean array: [ True False True False True] Selected elements: [10 30 50]

Example: Filtering Items Greater Than 5

In this example, items greater than 5 are returned as a result of Boolean indexing.

import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print('Our array is: \n', x) print('The items greater than 5 are:' , x[x > 5])

When we run above program, it produces following result:

Our array is: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] The items greater than 5 are: [ 6 7 8 9 10 11]

Example: Removing NaN Values

In this example, NaN (Not a Number) elements are omitted by using ~ (complement operator).

import numpy as np a = np.array([np.nan, 1,2,np.nan,3,4,5]) print(a[~np.isnan(a)])

When we run above program, it produces following result:

[1. 2. 3. 4. 5.]

Example: Filtering Complex Numbers

The following example shows how to filter out the complex numbers from an array.

import numpy as np a = np.array([1, 2+6j, 5, 3.5+5j]) print(a[np.iscomplex(a)])

Output of the above code is as follows:

[2. +6.j 3.5+5.j]

Example: Extracting Even Numbers

Let us see how to extract even numbers from an array using boolean indexing:

import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print('The even numbers are:', x[x % 2 == 0])

Following is the output of the above code:

The even numbers are: [2 4 6 8]