There is a function blockshapedthat does something pretty close to what you want:
In [81]: arr
Out[81]:
array([[ 0, 1, 2, 3, 4],
[ 4, 5, 6, 7, 8],
[ 8, 9, 10, 11, 12],
[12, 13, 14, 15, 16]])
In [82]: blockshaped(arr[:,:4], 2,2)
Out[82]:
array([[[ 0, 1],
[ 4, 5]],
[[ 2, 3],
[ 6, 7]],
[[ 8, 9],
[12, 13]],
[[10, 11],
[14, 15]]])
In [83]: blockshaped(arr[:,:4], 2,2).shape
Out[83]: (4, 2, 2)
, , , ( ), sum .
, , , sub_sums :
import numpy as np
def sub_sums(arr, nrows, ncols):
h, w = arr.shape
h = (h
w = (w
arr = arr[:h,:w]
return (arr.reshape(h
.swapaxes(1, 2)
.reshape(h
arr = np.asarray([range(0, 5),
range(4, 9),
range(8, 13),
range(12, 17)])
print(sub_sums(arr, 2, 2))
[[10 18]
[42 50]]
: Ophion - np.einsum :
def sub_sums_ophion(arr, nrows, ncols):
h, w = arr.shape
h = (h
w = (w
arr = arr[:h,:w]
return np.einsum('ijkl->ik', arr.reshape(h
In [105]: %timeit sub_sums(arr, 2, 2)
10000 loops, best of 3: 112 µs per loop
In [106]: %timeit sub_sums_ophion(arr, 2, 2)
10000 loops, best of 3: 76.2 µs per loop