How to Access Different Rows of a Multidimensional NumPy Array
When we need to access different rows of a multidimensional NumPy array such as first row, last two rows or middle rows it can be done using slicing. NumPy provides simple ways to select specific rows according to given conditions.
In 2D Array
Example 1: Accessing the First and Last row of a 2D NumPy array
import numpy as np
arr = np.array([[10, 20, 30], [40, 5, 66], [70, 88, 94]])
print("Array:")
print(arr)
res = arr[[0,2]]
print("Accessed Rows :")
print(res)
Output
Array: [[10 20 30] [40 5 66] [70 88 94]] Accessed Rows : [[10 20 30] [70 88 94]]
Example 2: Accessing the Middle row of 2D NumPy array
import numpy as np
arr = np.array([[101, 20, 3, 10], [40, 5, 66, 7], [70, 88, 9, 141]])
print("Array:")
print(arr)
res_arr = arr[1]
print("Accessed Row :")
print(res_arr)
Output
Array: [[101 20 3 10] [ 40 5 66 7] [ 70 88 9 141]] Accessed Row : [40 5 66 7]
In 3D Arrays
Example 1: Accessing the Middle rows of 3D NumPy array
import numpy as np
n_arr = np.array([[[10, 25, 70], [30, 45, 55], [20, 45, 7]], [[50, 65, 8], [70, 85, 10], [11, 22, 33]]])
print("Array:")
print(n_arr)
res_arr = n_arr[:,[1]]
print("Accessed Rows:")
print(res_arr)
Output
Array: [[[10 25 70] [30 45 55] [20 45 7]] [[50 65 8] [70 85 10] [11 22 33]]] Accessed Rows: [[[30 45 55]] [[70 85 10]]]
Example 2: Accessing the First and Last rows of 3D NumPy array
import numpy as np
n_arr = np.array([[[10, 25, 70], [30, 45, 55], [20, 45, 7]],
[[50, 65, 8], [70, 85, 10], [11, 22, 33]],
[[19, 69, 36], [1, 5, 24], [4, 20, 96]]])
print("Array:")
print(n_arr)
res_arr = n_arr[:,[0, 2]]
print("Accessed Rows:")
print(res_arr)
Output
Array:
[[[10 25 70]
[30 45 55]
[20 45 7]]
[[50 65 8]
[70 85 10]
[11 22 33]]
[[19 69 36]
[ 1 5 24]
[ 4 20 96]]]
Accessed Rows:
[[[10 25 70]
[20 45 7]]
[[50 65 8]
[11 22 33]]
[[19 69 36]
[ 4 20 96]]]