Numpy Array Indexing or Accessing Array Elements
We can access an array element by referring to its index number. Array indexing is the same as accessing an array element.
The indexes in NumPy arrays start with 0.
Example- Following example shows that how to access the first element of given array arr. First element of the array has index 0, Second element of the array has index 1 and similarly we can say that nth element of the array has index n-1.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
print(arr[1])
Output
1
2
How to Access 2-D Arrays?
We can use comma separated integers representing the dimension and the index of the element to access elements from 2-D arrays.
Example- Following example shows that how to access the element on the first row, third column:
import numpy as np
arr = np.array([[1,2,3,4], [5,6,7,8]])
print('3rd element on 1st row: ', arr[0, 2])
Output
3rd element on 1st row: 3
How to Access 3-D Arrays?
We can use comma separated integers representing the dimensions and the index of the element to access elements from 3-D arrays as shown in following example.
Example- Following example shows that how to access the second 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, 1])
Output-
5
Explaination of above example-
arr[0, 1, 1] prints the value 5, as shown in above output.
Reason:
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 1, we end up with the second value:
5
Negative Indexing
Negative indexing is used to access an array from the end
Example- Following example shows that how to access last element from the 2nd Dimension
import numpy as np
arr = np.array([[1,2,3], [4,5,6]])
print('Last element from 2nd dim: ', arr[1, -1])
Output-
6
Leave a Reply