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]]
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))
Demo:
np.random.seed(365) c = np.arange(24).reshape((4, 6)) print(c) print(blockshaped(c, 2, 3))
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!