لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science NumPy Array Indexing

Access Array Elements

Array indexing is the same as accessing an array element. One can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Example 1: Get the first element from the following array

Code

import numpy as np

arr = np.array([5, 7, 8, 9])

print(arr[0])

the output will be

5

Example 2: Get the second element from the following array.

Code

import numpy as np

arr = np.array([11, 12, 13, 14])
print(arr[1])

the output will be

12

Example 3: Get third and fourth elements from the following array and add them.

Code

import numpy as np

arr = np.array([15, 22, 33, 44])

print(arr[2] + arr[3])

the output will be

12

Access 2-D Arrays

In order to access elements from 2-D arrays we can use comma separated integers representing the dimension and the index of the element.

Example 4: Access the element on the first row, second column

Code

import numpy as np

arr = np.array([[11,12,13,14,15], [16,17,18,19,20]])

print('2nd element on 1st row: ', arr[0, 1])

the output will be

2nd element on 1st row: 12

Example 5: Access the element on the 2nd row, 5th column.

Code

import numpy as np

arr = np.array([[11,12,13,14,15], [16,17,18,19,20]])

print('5th element on 2nd row: ', arr[1, 4])

the output will be

5th element on 2nd row: 20

Access 3-D Arrays

To access elements from 3-D arrays we can use comma separated integers representing the dimensions and the index of the element.

Example 6: Access the third element of the second array of the first array.

Code

import numpy as np

arr = np.array([[[11, 12, 13], [14, 15, 16]], [[17, 18, 19], [20, 21, 22]]])

print(arr[0, 1, 2])

the output will be

16

Explaination

arr[0, 1, 2] prints the value 16.

And this is why.

The first number represents the first dimension, which contains two arrays

[[11, 12, 13], [14, 15, 16]]

and

[[17, 18, 19], [20, 21, 22]]

Since we selected 0, we are left with the first array

[[11, 12, 13], [14, 15, 16]]

The second number represents the second dimension, which also contains two arrays.

[11, 12, 13]

and

[14, 15, 16]

Since we selected 1, we are left with the second array.

[14, 15, 16]

The third number represents the third dimension, which contains three values.

14

15

16

Since we selected 2, we end up with the third value.

16

Negative Indexing

Negative indexing is used to access an array from the end.

Example 7: Print the last element from the 2nd dim.

Code

import numpy as np

arr = np.array([[11,12,13,14,15], [16,17,18,19,20]])

print('Last element from 2nd dim: ', arr[1, -1])

the output will be

Last element from 2nd dim: 20