Home > Backend Development > Python Tutorial > How can I divide a NumPy 2D array into smaller 2D arrays?

How can I divide a NumPy 2D array into smaller 2D arrays?

Mary-Kate Olsen
Release: 2024-11-09 07:44:02
Original
323 people have browsed it

How can I divide a NumPy 2D array into smaller 2D arrays?

Slicing 2D Arrays into Smaller Arrays

Problem:
You wish to fragment a two-dimensional (2D) NumPy array into smaller 2D arrays. For instance, you may want to transform a 2x4 array into two 2x2 arrays.

Solution:
A combination of reshape and swapaxes functions allows you to divide your array into "blocks." Here's a Python implementation that achieves this:

def blockshaped(arr, nrows, ncols):
    h, w = arr.shape
    assert h % nrows == 0, f"{h} rows is not evenly divisible by {nrows}"
    assert w % ncols == 0, f"{w} cols is not evenly divisible by {ncols}"

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

In this solution:

  • nrows and ncols define the dimensions of each smaller array.
  • You must ensure that the input array is evenly divisible by these values.
  • The reshape function rearranges the array into blocks.
  • The swapaxes function swaps the axes to obtain the desired shape.
  • The final reshape flattens the array into a sequence of smaller blocks.

Example:

Consider the following input array:

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

print(c)

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

Using blockshaped with nrows=2 and ncols=3, you can fragment this array into the following blocks:

print(blockshaped(c, 2, 3))

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

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

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

 [[15 16 17]
  [21 22 23]]]
Copy after login

This demonstration illustrates how you can slice a 2D array into smaller rectangular arrays of specified dimensions.

The above is the detailed content of How can I divide a NumPy 2D array into smaller 2D arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template