Python Program to Get Specific Row from Numpy Array

Get a Row from Numpy Array

To get specific row of elements, access the numpy array with all the specific index values for other dimensions and : for the row of elements you would like to get. It is special case of array slicing in Python.

For example, consider that we have a 3D numpy array of shape (m, n, p). And we would like to get the row of elements at ith element along axis=0, and kth element along axis=2. Use the following syntax to get this desired row of elements.

row = ndarray[i, :, k]

Examples

1. Access a specific row of elements in given 3D numpy array

In the following example, we will initialize a 3D array and access a specific row of elements present at index=0 along axis=0, and index=1 along axis=2.

Python Program

import numpy as np

# Initialize an array
arr = np.array([[[11, 11, 9, 9],
                 [11, 0, 2, 0]],
                [[10, 14, 9, 14],
                 [0, 1, 11, 11]]])

# Print shape of array
print('Array Shape: ',arr.shape)

# Get the desired row
row = arr[0, :, 1]
print('Desired Row of Elements: ', row)
Run Code Copy

Output

Array Shape:  (2, 2, 4)
Desired Row of Elements:  [11  0]

2. Access a specific row or column in 2D Numpy Array

In the following example, we will initialize a 2D array and access a row and column using array slicing.

Python Program

import numpy as np

# Initialize an array
arr = np.array([[11, 11, 9, 9],
                [11,  0, 2, 0]])

print('Array\n',arr)
				
# Get index=1 along axis=0 - this means a row in 2D
row = arr[1, :]
print('arr[1, :] : ', row)

# Get index=2 along axis=1 - this means a column in 2D
row = arr[:, 2]
print('arr[:, 2] : ', row)
Run Code Copy

Output

Array
 [[11 11  9  9]
 [11  0  2  0]]
arr[1, :] :  [11  0  2  0]
arr[:, 2] :  [9 2]

Summary

In this Numpy Tutorial, we learned how to access a row from a Numpy 2D and 3D arrays, with the help of well detailed example programs.

Code copied to clipboard successfully 👍