Home >Backend Development >Python Tutorial >How to Slice a 2D Numpy Array into Smaller 2D Arrays?
Numpy is a versatile library for manipulating multidimensional arrays in Python. It offers various methods for array manipulation, including slicing to extract specific sections. This article explores a solution for slicing a 2D array into smaller 2D arrays, emulating the provided example:
[[1,2,3,4], -> [[1,2] [3,4] [5,6,7,8]] [5,6] [7,8]]
The suggested solution leverages the reshape and swapaxes functions to achieve the desired slicing. The reshape function modifies the array's shape, and the swapaxes function交换es the specified axes. In the following Python code, the blockshaped function encapsulates this approach:
def blockshaped(arr, nrows, ncols): h, w = arr.shape return (arr.reshape(h//nrows, nrows, -1, ncols) .swapaxes(1,2) .reshape(-1, nrows, ncols))
Explanation:
To illustrate the usage, consider the sample array c:
np.random.seed(365) c = np.arange(24).reshape((4, 6))
Slicing c into 2x3 blocks:
sliced = blockshaped(c, 2, 3)
sliced will hold the desired 2D blocks:
[[[ 0 1 2] [ 6 7 8]] [[ 3 4 5] [ 9 10 11]] [[12 13 14] [18 19 20]] [[15 16 17] [21 22 23]]]
This solution demonstrates how to slice a 2D numpy array into smaller 2D arrays using the reshape and swapaxes functions. It provides a flexible and efficient approach for processing and manipulating images or other matrices.
The above is the detailed content of How to Slice a 2D Numpy Array into Smaller 2D Arrays?. For more information, please follow other related articles on the PHP Chinese website!