Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

NumPy - Indexing



Indexing refers to finding or accessing a particular item or position in an organized list or data structure such as trees, lists, strings, arrays, graphs, matrices, etc. This technique lets us choose one or a group of elements from a data set.

Indexing in NumPy

NumPy indexing is a method to access or change specific values in an array using their position. Each position has a number called an index. Positive numbers count from the start (0, 1, 2, ), and negative numbers count backward (-1 for the last, -2 for the second last, etc.).

In NumPy, indexing has an important role in working with large arrays. It simplifies data operations and speeds up analysis by directly referencing array positions. This makes data manipulation and analysis faster.

Python uses indexing to get items from lists or tuples starting at index 0. In contrast, NumPy indexing works with multi-dimensional arrays and offers more advanced techniques. These include slicing, boolean indexing, and advanced indexing.
NumPy Indexing

Simple Indexing

Simple indexing in NumPy allows you to use an array's location to access particular items. For a 1D array, use a single index like arr[2]. For 2D arrays, you have to give both row and column indices, such as arr[1, 2]. For 3D arrays, you need to provide depth, row, and column indices, like this: arr[2, 0, 1].

Let's us take a few examples to understand simple indexing −

Accessing 1D array using Indexing

Let's say we have a grocery list with vegetables and fruits. Suppose we want to access banana in the grocery list we use arr[3] where 3 is index for banana. Following is the code −

import numpy as np
grocery_list = ['carrot', 'beetroot', 'brinjal', 'banana', 'mango', 'potato', 'apple']
arr = np.array(grocery_list)
print(arr[3]) 

Following is an output of the above code −

banana

Accessing 2D Array Using Indexing

Let us create a 2D array on the grade book where each row represents a student and each column represents the student's exam score in different subjects. We need to access student 2's score in the third subject.

Accesses the student 2's score(index 1) and 3rd column (subject 3) which is '78' (index 2) we use student_score[1,2].

2D Indexing in NumPy
import numpy as np
student_score = np.array([['99', '87', '63'],
                     ['100', '98', '78'],
                     ['95', '100', '76']])
print("Student 2's score in 3rd subject :", student_score[1,2])

Output of the above code is as follows −

Student 2's score in 3rd subject : 78

Accessing 3D Array Using Indexing

First, let us create a 1D array with a sequence of numbers ranging from 1 to 26 using arange() function then we will convert this 1D to 3D using reshape() function. Using the index we will finally access particular elements of the 3D array based on their positions.

To access the element at the third depth (index 2), 0th row, and 3rd column (index 2), we use arr_3d[2, 0, 2].

import numpy as np
arr = np.arange(27)
arr_3d = arr.reshape(3,3,3)
print("3D array is :\n", arr_3d)
print("Element:",arr_3d[2,0,2])

Output of the above code is as follows −

Element: 20

Negative Indexing in NumPy

We use negative indexing to access elements from the end of an array. The index -1 refers to the last element in the array, -2 refers second last, and so on. It is mostly useful for accessing elements in reverse order in multi-dimensional arrays.

Example

Following is an example of the negative indexing in NumPy −

import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[-1])
print(arr[-3])

Following is an output of the above code −

50
30

Types of Indexing in NumPy

NumPy has a number of ways to access and manipulate array items. From simple indexing to advanced indexing, they provide you with more flexibility and control over your data. The following are the types of indexing -

  • Basic Indexing: Basic indexing involves using integers or slices to obtain specific elements or ranges. This method generates a view of the original array.

  • Advanced Indexing: With this method, you can extract elements using arrays or lists of indices. This can generate copies of the original array and allow for more complex selections, such as non-contiguous elements.

  • Field access: Field access is used for structured arrays to access or manipulate specific fields of the array. It provides an efficient way to handle heterogeneous data similar to columns in a table.

Basic Indexing

Basic indexing uses integers or slice objects to access an individual or a group of elements in the array. Basic slicing applies when you use one of the following methods:

  • Slice Object: Created using the format start: stop: step.

  • Single Integer: Accesses an element at a specific index.

  • Combination of Integers and Slice Objects: A mix of integers and slice objects (e.g., start: stop, or a tuple containing both).

All arrays generated by basic slicing are always views of the original array.

Example: Slicing with Start, Stop, and Step parameter

In the below example, an ndarray object is prepared by the arange() function. Then a slice object is defined with start, stop, and step values 2, 7, and 2 respectively.

When this slice object is passed to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced.

import numpy as np 
a = np.arange(12) 
print(a)
#using start:stop:step format
print(a[2:7:2])

Following is an output of the above code −

[ 0  1  2  3  4  5  6  7  8  9 10 11]
[2 4 6]

Example: Accessing Specific Rows and Elements

Let us create a 2D array for a classroom representing a seating chart where each row represents rows of seats and each column represents individual seats. Now let us extract a specific row and specific seat using a single integer.

The arr_2d[2, 0] accesses the element in the 3rd row and 1st column (indexing starts at 0). Following is the code −

import numpy as np
arr = np.arange(12)
arr_2d = arr.reshape(3, 4)
print("arr_2d:\n",arr_2d)
#Using single integer
print("Element at 8th position is:",arr_2d[2,0])

Following is an output of the above code −

arr_2d:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
Element at 8th position is: 8

Example: Reshaping and Element Selection

In the below code we have created a 3D array and accessed the elements in the 2nd row (index1) from column indices 2 up to (but not including) index 4 using arr_3d[1, 2:4].

import numpy as np
arr = np.arange(12)
arr_3d = arr.reshape(3, 4)
print(arr_3d[1, 2:4])

Following is an output of the above code −

[6 7]
Advertisements