How do I slice a 2D NumPy array?

To slice a 2D NumPy array, you can use the syntax array[row_start:row_end, col_start:col_end] to select the desired part of the array. This syntax will select the elements from row_start to row_end, and from col_start to col_end, both inclusive. If any of these indices are not specified, the entire range of the array will be selected.


You can use the following methods to slice a 2D NumPy array:

Method 1: Select Specific Rows in 2D NumPy Array

#select rows in index positions 2 through 5
arr[2:5, :]

Method 2: Select Specific Columns in 2D NumPy Array

#select columns in index positions 1 through 3
arr[:, 1:3]

Method 3: Select Specific Rows & Columns in 2D NumPy Array

#select rows in range 2:5 and columns in range 1:3
arr[2:5, 1:3]

The following examples show how to use each method in practice with the following 2D NumPy array:

import numpy as np

#create NumPy array
arr = np.arange(24).reshape(6,4)

#view NumPy array
print(arr)

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]

Example 1: Select Specific Rows of 2D NumPy Array

We can use the following syntax to select the rows in index positions 2 through 5:

#select rows in index positions 2 through 5
arr[2:5, :]

array([[ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

Note that the syntax 2:5 tells NumPy to select rows 2 up to 5, but doesn’t include 5.

Thus, this syntax selects all of the values in the rows with index positions of 2, 3 and 4.

Example 2: Select Specific Columns of 2D NumPy Array

We can use the following syntax to select the columns in index positions 1 through 3:

#select columns in index positions 1 through 3
arr[, 1:3]

array([[ 1,  2],
       [ 5,  6],
       [ 9, 10],
       [13, 14],
       [17, 18],
       [21, 22]]))

Thus, this syntax selects all of the values in the columns with index positions of 1 and 2.

Example 3: Select Specific Rows & Columns of 2D NumPy Array

We can use the following syntax to select the rows in index positions 2 through 5 and the columns in index positions 1 through 3:

#select rows in 2:5 and columns in 1:3
arr[2:5, 1:3]

array([[ 9, 10],
       [13, 14],
       [17, 18]])

This syntax returns all of the values in the 2D NumPy array between row index positions 2 through 5 and column index positions 1 through 3.

The following tutorials explain how to perform other common operations in NumPy:

x