Home  >  Article  >  Backend Development  >  How to Slice a 2D Array into Smaller 2D Arrays with NumPy?

How to Slice a 2D Array into Smaller 2D Arrays with NumPy?

DDD
DDDOriginal
2024-11-07 16:21:02601browse

How to Slice a 2D Array into Smaller 2D Arrays with NumPy?

Slicing a 2D Array into Smaller 2D Arrays with Numpy

Often, it becomes necessary to split a 2D array into smaller 2D arrays. For instance, consider the task of dividing a 2x4 array into two 2x2 arrays.

Solution:

A combination of reshape and swapaxes functions proves effective in this scenario:

import numpy as np

def blockshaped(arr, nrows, ncols):
    """
    Converts a 2D array into a 3D array with smaller subblocks.
    """
    h, w = arr.shape
    assert h % nrows == 0, f"{h} rows is not divisible by {nrows}"
    assert w % ncols == 0, f"{w} columns is not divisible by {ncols}"

    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

Example Usage:

Consider the following array:

c = np.arange(24).reshape((4, 6))
print(c)

Output:

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]

Slicing this array into smaller blocks:

print(blockshaped(c, 2, 3))

Output:

[[[ 0  1  2]
  [ 6  7  8]]

 [[ 3  4  5]
  [ 9 10 11]]

 [[12 13 14]
  [18 19 20]]

 [[15 16 17]
  [21 22 23]]]

Additional Notes:

  • The unblockshaped function can be used to reverse the slicing.
  • Superbatfish's blockwise_view provides an alternative with its distinct format.

The above is the detailed content of How to Slice a 2D Array into Smaller 2D Arrays with NumPy?. 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