Now that we have learned about indexing arrays in numpy, it’s time to learn about slicing in numpy. We can slice arrays by providing a query of index range that we want to be structured.

In order to ‘slice’ in numpy, you will use the colon (:) operator and specify the starting and ending value of the index. Remember the last value won’t be sliced but it’s used as a flag to indicate all the values that are present before it.

Single Dimensional Slicing in Numpy

If you want to access or slice the elements of a single dimensional array then you have to specify starting or ending value.

import numpy as np slice_arr = np.array([1,2,3,4,5]) slice_arr slice_arr[0:2]

Here you can see that all the elements starting from 0 to just before 2 are all printed.

2D Slicing

Let’s learn about 2D slicing now, this concept is very important to apply in machine learning as well. Think of 2D slicing as two coordinates (x,y) separated by a comma where you define your range of slicing for a row first and then specify the range of slicing for a column.

slice_arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])


array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])

Slicing the portion of the 2D array



array([[2, 3, 4],
       [7, 8, 9]])

The first portion (0:2) selects rows starting at 0 and ending before 2, the second portion selects columns (1:4) and whatever elements are intersecting, that part is sliced from the original array.