I have a 2D array t in numpy:
>>> t = numpy.array(range(81)).reshape((9,9))
>>> t
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, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])
It is indexed by two numbers: row and column index.
>>> t[2,3]
21
>>> t.shape
(9, 9)
>>> t.strides
(72, 8)
What I want to do is to divide the array into rectangular cells of fixed size, 3×3 for example. I’d like to avoid memory copying. The way I try to achieve this is creating a view onto t with correspondent shape and strides ((3,3,3,3) and (216,24,72,8) respectively). This way the first two indexes of the view would mean the position of 3×3 cell in the larger grid and the last two would mean the position of element inside the cell. For example, t[0,1,:,:] would return
array([[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23]])
So my question is — how to create the described view? Am I missing a simpler method? Can this be done elegantly with slicing syntax?
Edit: A way that does not require you to figure out the strides yourself is
[end of edit]
Another way to achieve this is to use
numpy.lib.stride_tricks.as_strided:Note that the strides you provided are correct only for float arrays (
itemsize == 8), while the exampletin your post is anintarray (which might or might no haveitemsize == 8).