Home > Backend Development > Python Tutorial > 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
Release: 2024-11-07 16:21:02
Original
670 people have browsed it

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))
Copy after login

Example Usage:

Consider the following array:

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

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]]
Copy after login

Slicing this array into smaller blocks:

print(blockshaped(c, 2, 3))
Copy after login

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]]]
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template