How to crop an array in Python

Do The Thing
Dec 10, 2022

--

To crop an array in Python, you can use the slicing operator (:). Here is an example:

# Import the NumPy library
import numpy as np

# Create a 4x4 array
array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])

# Crop the array to get a 3x3 sub-array starting from (1,1)
cropped_array = array[1:4, 1:4]

# Print the cropped array
print(cropped_array)

This will print the following output:

[[ 6  7  8]
[10 11 12]
[14 15 16]]

As you can see, the slicing operator allows you to select a sub-array by specifying the starting and ending indices along each dimension. In this example, we started at index 1 and ended at index 4 along both dimensions, which results in a 3x3 sub-array.

--

--

Do The Thing
Do The Thing

No responses yet