有另一个问题 http://stackoverflow.com/a/13990648/190597几个月前,这让我想到了使用reshape
and swapaxes
. The h//nrows
这是有道理的,因为这将第一个块的行保持在一起。这也是有道理的,你需要nrows
and ncols
成为形状的一部分。-1
告诉 reshape 填充使 reshape 有效所需的任何数字。有了解决方案的形式,我就不断尝试,直到找到可行的公式。
您应该能够使用某种组合将数组分成“块”reshape
and 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, 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))
turns c
np.random.seed(365)
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]]
into
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]]]
我已经发布了一个反函数,unblockshaped, here https://stackoverflow.com/a/16873755/190597,以及 N 维推广here https://stackoverflow.com/a/42298440/190597。概括可以更深入地了解该算法背后的推理。
请注意,还有超级蝙蝠鱼的blockwise_view https://stackoverflow.com/a/28207538/190597。它安排了
不同格式的块(使用更多轴)但它具有以下优点:(1)
总是返回一个视图并且(2)能够处理任何数组
方面。