你应该能够打破你的数组转换成“块”使用的一些组合reshape
和swapaxes
:
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 should look like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
h, w = arr.shape
assert h % nrows == 0, "{} rows is not evenly divisble by {}".format(h, nrows)
assert w % ncols == 0, "{} cols is not evenly divisble by {}".format(w, ncols)
return (arr.reshape(h//nrows, nrows, -1, ncols)
.swapaxes(1,2)
.reshape(-1, nrows, ncols))
转弯 c
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]]]
我已经张贴了[反函数,unblockshaped
在这里](http://codingdict.com/questions/164064,和N维泛化这里。泛化使该算法背后的原因有了更多的了解。
注意,还有超级蝙蝠blockwise_view
鱼的。它以不同的格式(使用更多的轴)排列块,但是它的优点是(1)始终返回视图,并且(2)能够处理任何尺寸的数组。