NumPy Array Indexing

Course recommendations:

Access array elements

Array indices are equivalent to accessing array elements.

You can access array elements by referencing their index numbers.

Example

The indices in NumPy arrays start at 0, which means the index of the first element is 0, the index of the second element is 1, and so on.

import numpy as np
arr = np.array([1, 2, 3, 4])
Access the first element from the following array:

Run Example

Example

Get the 1st element from the following array:

import numpy as np
arr = np.array([1, 2, 3, 4])
Get the 2nd element from the following array:

Run Example

Example

Get the 3rd and 4th elements from the following array and add them together:

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])

Run Example

Access 2-D array

To access elements in a 2-D array, we can use comma-separated integers to represent the dimensions and indices of the elements.

Example

Access the 2nd element in the 1st dimension:

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st dim: ', arr[0, 1])

Run Example

Example

Access the 5th element in the 2nd dimension:

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd dim: ', arr[1, 4])

Run Example

Access 3-D array

To access elements in a 3-D array, we can use comma-separated integers to represent the dimensions and indices of the elements.

Example

Access the third element of the second array of the first array:

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])

Run Example

Example Explanation

arr[0, 1, 2] Print Value 6.

Working Principle:

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

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

Then:

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

Because we selected 0, so the remaining first array is:

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

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

[1, 2, 3]

Then:

[4, 5, 6]

Because we selected 1, so the remaining second array is:

[4, 5, 6]

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

4
5
6

Because we selected 2, so the final value obtained is the third one:

6

Negative Indexing

Use negative indexing to access the array from the end.

Example

Print the last element of 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])

Run Example