The term slicing in programming usually refers to obtaining a substring, sub-tuple, or sublist from a string, tuple, or list respectively.
Python offers an array of straightforward ways to slice not only these three but any iterable. An iterable is, as the name suggests, any object that can be iterated over.
In this article, we'll go over everything you need to know about Slicing Numpy Arrays in Python.
NumPy Array slicing
The most common way to slice a NumPy array is by using the
: operator with the following syntax:
start parameter represents the starting index,
end is the ending index, and
step is the number of items that are "stepped" over.
NumPy is a free Python package that offers, among other things, n-dimensional arrays.
Slicing 1D (one dimensional) arrays in NumPy can be done with the same notation as slicing regular lists in Python:
import numpy as np arr = np.array([1,2,3,4]) print(arr[1:3:2]) print(arr[:3]) print(arr[::2])
 [1 2 3] [1 3]
2D NumPy Array Slicing
A 2D array in NumPy is an array of arrays, a 3D array is an array of arrays of arrays and so forth. A 2D array can be represented as a matrix like so:
import numpy arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(arr)
Let's print this matrix out:
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
Slicing a 2D array can eighter result in an array or a matrix. The syntax that results in a matrix would be:
The syntax that results in an array:
arr[startx:endx:stepx, const] arr[const, starty:endy:stepy]
Utilizing this syntax results in a matrix who's elements are the colums in the range from
endx on the x-axis, and rows in the range from
endy on the y-axis of the original matrix:
Let's take a look at how we can slice this matrix and what the slicing results in:
import numpy arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print("The original matrix:") print(arr) print("A sliced submatrix:") print(arr[1:4,2:4]) print("A sliced subarray:") print(arr[1,:]) print("A sliced submatrix:") print(arr[:,3:]) print("A sliced subarray:") print(arr[:,3])
This code segment prints out:
The original matrix: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] A sliced submatrix: [[ 7 8] [11 12] [15 16]] A sliced subarray: [5 6 7 8] A sliced submatrix: [[ 4] [ 8]  ] A sliced subarray: [ 4 8 12 16]
Slicing any sequence in Python is easy, simple, and intuitive. Negative indexing offers an easy way to acquire the first or last few elements of a sequence, or reverse its order.
In this article, we've covered how to slice Python's NumPy arrays.