Home > Backend Development > Python Tutorial > How to Slice a 2D Array into Smaller 2D Subarrays in NumPy?

How to Slice a 2D Array into Smaller 2D Subarrays in NumPy?

Mary-Kate Olsen
Release: 2024-11-08 07:08:02
Original
313 people have browsed it

How to Slice a 2D Array into Smaller 2D Subarrays in NumPy?

Slicing 2D Arrays into Smaller 2D Subarrays

Question:
Can we subdivide a 2D array into smaller 2D arrays in NumPy?

Example:
Transform a 2x4 array into two 2x2 arrays:

[[1,2,3,4]   ->    [[1,2] [3,4]
 [5,6,7,8]]          [5,6] [7,8]]
Copy after login

Mechanism:

Instead of creating new arrays, a better approach is to reshape the existing array using reshape() and swap axes using swapaxes().

Blockshaped Function:

Below is the implementation of the blockshaped function:

def blockshaped(arr, nrows, ncols):
    """
    Partitions an array into blocks.

    Args:
        arr (ndarray): The original array.
        nrows (int): Number of rows in each block.
        ncols (int): Number of columns in each block.

    Returns:
        ndarray: Partitioned array.
    """
    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

Demo:

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

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

Alternative Solution:

SuperBatFish's blockwise_view provides another option, offering a different block arrangement and view-based representation.

The above is the detailed content of How to Slice a 2D Array into Smaller 2D Subarrays in 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template