You can use the following syntax to get a specific row from a NumPy array:
#get row in index position 2 from NumPy array
my_array[2, :]
The following examples shows how to use this syntax in practice.
Example 1: Get One Row from NumPy Array
The following code shows how to get one specific row from a NumPy array:
import numpy as np #create NumPy array data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) #view NumPy array print(data) array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) #get row in index position 2 data[2, :] array([ 9, 10, 11, 12])
Notice that only the row in index position 2 of the NumPy array is returned.
Example 2: Get Multiple Rows from NumPy Array
The following code shows how to get multiple rows from a NumPy array:
import numpy as np #create NumPy array data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) #view NumPy array data array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) #get rows in index positions 0 and 2 from NumPy array data[[0,2], :] array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]])
Example 3: Get Rows in Range from NumPy Array
The following code shows how to get rows in a range from a NumPy array:
import numpy as np #create NumPy array data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) #view NumPy array data array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) #get rows in index positions 0 through 1 data[0:2, :] array([[1, 2, 3, 4], [5, 6, 7, 8]])
Note that the last value in the range (in this case, 2) is not included in the range of rows that is returned.
Additional Resources
The following tutorials explain how to perform other common operations in NumPy:
How to Get Specific Column from NumPy Array
How to Map a Function Over a NumPy Array
How to Add a Column to a NumPy Array