问题是这个问题的反面。我正在寻找一种通用方法,以从小数组中提取原始的大数组:
array([[[ 0, 1, 2], [ 6, 7, 8]], [[ 3, 4, 5], [ 9, 10, 11]], [[12, 13, 14], [18, 19, 20]], [[15, 16, 17], [21, 22, 23]]]) -> array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
我目前正在开发一个解决方案,将在完成后发布,但是希望看到其他(更好)的方法。
import numpy as np def blockshaped(arr, nrows, ncols): “”“ Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size
If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape return (arr.reshape(h//nrows, nrows, -1, ncols) .swapaxes(1,2) .reshape(-1, nrows, ncols)) def unblockshaped(arr, h, w): """ Return an array of shape (h, w) where h * w = arr.size If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), then the returned array preserves the "physical" layout of the sublocks. """ n, nrows, ncols = arr.shape return (arr.reshape(h//nrows, -1, nrows, ncols) .swapaxes(1,2) .reshape(h, w))
例如,
c = np.arange(24).reshape((4,6)) print(c) # [[ 0 1 2 3 4 5] # [ 6 7 8 9 10 11] # [12 13 14 15 16 17] # [18 19 20 21 22 23]] print(blockshaped(c, 2, 3)) # [[[ 0 1 2] # [ 6 7 8]] # [[ 3 4 5] # [ 9 10 11]] # [[12 13 14] # [18 19 20]] # [[15 16 17] # [21 22 23]]] print(unblockshaped(blockshaped(c, 2, 3), 4, 6)) # [[ 0 1 2 3 4 5] # [ 6 7 8 9 10 11] # [12 13 14 15 16 17] # [18 19 20 21 22 23]]
注意,还有超级蝙蝠blockwise_view鱼的 。它以不同的格式(使用更多的轴)排列块,但是它的优点是(1)始终返回视图,并且(2)能够处理任何尺寸的数组。
blockwise_view