Home >Backend Development >Python Tutorial >How to Slice a 2D Numpy Array into Smaller 2D Arrays?

How to Slice a 2D Numpy Array into Smaller 2D Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 21:27:02704browse

How to Slice a 2D Numpy Array into Smaller 2D Arrays?

Slicing 2D Arrays into Smaller 2D Arrays with Numpy

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 Reshape and Swapaxes Approach

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:

  • h, w = arr.shape: Stores the dimensions of the input array arr.
  • arr.reshape(h//nrows, nrows, -1, ncols): Reshapes the array into a 4-dimensional array. The first two dimensions ensure that it has h/nrows blocks, each containing nrows rows. The third dimension is used to preserve the columns, and the fourth dimension has ncols columns in each block.
  • swapaxes(1,2): Swapaxes the second and third dimensions, which effectively permutes the blocks along the rows and columns.
  • reshape(-1, nrows, ncols): Reshapes the array back to the desired shape, consisting of h/nrows * w/ncols 2D arrays, each with nrows and ncols.

Example Usage

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]]]

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn