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))
In this solution:
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]]
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]]]
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!