Accessing Array Elements
Accessing elements in an array is done using indexing.
In NumPy, you can retrieve any element by specifying its index number. It's important to note that indexing in NumPy starts at 0. This means the first element has an index of 0, the second element has an index of 1, and so on.
Program:
# Get the first element from the following array
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
Output:
1
Program:
# Get the Second element from the following array
import numpy as np
arr=np.array([1,2,3,4])
print(arr[1])
Output:
2
Program:
# Example: Get the third and fourth elements from the array and add them
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])
Output:
7
Accessing 2-D Array Elements
To access elements in a 2-D array, you can use a pair of comma-separated integers inside the square brackets. The first integer represents the row index, and the second represents the column index.
You can think of a 2-D array as a table with rows and columns. The first number specifies the row, and the second number specifies the column.
Program:
#Access the element in the first row, second column
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print('2nd element in 1st row:', arr[0, 1])
Output:
2
Program:
#Access the element in the second row, fifth column
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print('5th element in 2nd row:', arr[1, 4])
Output:
10
Accessing 3-D Array Elements
To access elements in a 3-D array, you use comma-separated integers inside square brackets. Each number represents a specific dimension and index.
Program:
#Access the third element of the second array in the first block
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Output:
6
Explanation
arr[0, 1, 2] returns the value 6.
The first index 0 selects the first block:
The first index 0 selects the first block:
[[1, 2, 3],
[4, 5, 6]]
The second index 1 selects the second array inside this block:
[4, 5, 6]
The third index 2 selects the third element in this array, which is 6.
Negative Indexing
You can also use negative indexing to access elements from the end of an array.
Program:
#Print the last element in the second row
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print('Last element in 2nd row:', arr[1, -1])
Output:
10