Introduction
Slicing helps you pick specific rows and columns from a table of data. It makes it easy to focus on the parts you want.
Slicing helps you pick specific rows and columns from a table of data. It makes it easy to focus on the parts you want.
array[row_start:row_end, col_start:col_end]
Rows and columns start counting at 0.
The end index is not included in the slice.
data[0:3, 1:4]
data[:, 2]data[5:10, :]
data[-3:, -2:]
This code shows how to slice rows and columns from a 2D numpy array. It prints the original array and three slices.
import numpy as np # Create a 5x5 array with numbers 0 to 24 data = np.arange(25).reshape(5,5) # Select rows 1 to 3 and columns 2 to 4 slice1 = data[1:4, 2:5] # Select all rows in column 0 slice2 = data[:, 0] # Select last 2 rows and last 3 columns slice3 = data[-2:, -3:] print("Original array:\n", data) print("\nSlice rows 1-3, cols 2-4:\n", slice1) print("\nAll rows, column 0:\n", slice2) print("\nLast 2 rows, last 3 columns:\n", slice3)
Remember that slicing does not copy data, it creates a view. Changing the slice changes the original array.
You can use negative numbers to count from the end.
Slicing lets you pick parts of rows and columns easily.
Use start:end to choose ranges; end is not included.
Use ':' to select all rows or columns.
array[1:3, 0:2] do on a 2D NumPy array?1:30:2arr?:, columns 2 to 4 means 2:5 because end is excluded.arr[:, 2:5] -> Option Bimport numpy as np
arr = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
print(arr[0:2, 1:3])data?
slice = data[1:3, 0:2]
1:31:3 selects rows 1 and 2 only, not row 3.0:2arr. How do you extract the middle 3 rows and middle 3 columns as a new array?arr[1:4, 1:4] -> Option CPass the test and this pattern moves unknown