Slicing means cutting out a chunk of an array. The syntax is start:stop:step, and the stop index isn't included. Slicing is extremely handy when you need to pick out certain rows/columns from a big chunk of data.
import numpy as np
numbers = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Index 2 to 5:", numbers[2:6])
print("Every 2 steps:", numbers[::2])
matrix = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
print("
First 2 rows, columns 1 to 2:
", matrix[:2, 1:3])numbers[2:6] grabs index 2 through 5. 6 isn't included. numbers[::2] grabs from start to end with a step of 2. For 2-D slicing, whatever comes before the comma refers to rows, and after the comma refers to columns.
Index 2 to 5: [2 3 4 5] Every 2 steps: [0 2 4 6 8] First 2 rows, columns 1 to 2: [[2 3] [6 7]]Info
A slice result can be a view into the original array, so in some cases modifying the slice will affect the original array too. If you want a fully independent copy, use .copy().