我想得到一个三维阵列的多个子阵列。我可以在二维情况下使用堆栈后的函数拆分数组:
def blockshaped(arr, nrows, ncols):
h, w = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
.swapaxes(1,2)
.reshape(-1, nrows, ncols))
所以我想把它扩展到3D数组的情况下,把块作为2D数组,但在第一维的每个切片中。我试着用一个“for循环”,但没用。。。在
例如:
^{pr2}$我得到了4个“子阵列”:
array([[[ 2., 1.],
[ 1., 1.]],
[[ 1., 1.],
[ 1., 1.]],
[[ 3., 1.],
[ 1., 1.]],
[[ 1., 1.],
[ 1., 1.]]])
但对于作为输入的三维阵列:
test2=np.array([[[ 2., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 3., 1., 1., 1.],
[ 1., 1., 1., 1.]],
[[ 5., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 2., 1., 1., 1.],
[ 1., 1., 1., 1.]]])
所以在这里我想要同样的分解但是在2个“切片”。。。在
def blockshaped(arr, nrows, ncols):
h, w, t = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
.swapaxes(1,2)
.reshape(-1, nrows, ncols))
我尝试使用“for循环”,但不起作用:
for i in range(test2.shape[0]):
sub = blockshaped(test[i,:,:], 2, 2)
你的循环解决方案可以做如下工作:
但是您可以稍微修改
^{pr2}$blockshaped()
,在切片前后重塑数据:相关问题 更多 >
编程相关推荐