Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Access 3-D Arrays

To access elements in three-dimensional (3-D) arrays, we can use comma-separated integers that represent the dimensions and the index of the element.

Example

Access the third element of the second array within the first array.

import numpy as np

arr = np.array([[[123], [456]], [[789], [101112]]])

print(arr[012])

Example Explained

The expression arr[0, 1, 2] yields the value 6 for the following reasons:

The first number indicates the first dimension, which contains two arrays:

[[1,2,3],[4,5,6]][[1, 2, 3], [4, 5, 6]] 

and

[[7,8,9],[10,11,12]][[7, 8, 9], [10, 11, 12]]

By selecting 0, we focus on the first array:

[[1,2,3],[4,5,6]][[1, 2, 3], [4, 5, 6]]

The second number refers to the second dimension, which also consists of two arrays:

[1,2,3][1, 2, 3] 

and

[4,5,6][4, 5, 6]

Choosing 1 leads us to the second array:

[4,5,6][4, 5, 6]

The third number corresponds to the third dimension, which contains three values:
4, 5, and 6.
By selecting 2, we arrive at the third value: 6.

Negative Indexing

Utilize negative indexing to access elements of an array from the end.

Example

Print the last element from the second dimension.

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print(‘Last element from 2nd dim: ‘, arr[1, –1])