I have a 3D NumPy array a
of shape (2, 9, 9)
like this one:
a = np.array([
[[4, 5, 1, 3, 8, 8, 0, 6, 6],
[9, 2, 2, 1, 8, 2, 2, 4, 5],
[2, 3, 2, 2, 5, 3, 1, 2, 4],
[9, 6, 2, 9, 1, 0, 6, 2, 3],
[4, 2, 7, 7, 9, 1, 3, 7, 2],
[5, 8, 9, 4, 6, 3, 1, 6, 7],
[3, 6, 4, 7, 2, 9, 8, 3, 4],
[0, 4, 1, 2, 3, 7, 3, 7, 5],
[6, 9, 2, 6, 0, 0, 5, 1, 4]],
[[4, 2, 0, 1, 6, 7, 1, 0, 8],
[1, 5, 3, 6, 4, 2, 4, 8, 3],
[7, 4, 9, 9, 1, 9, 7, 3, 1],
[3, 6, 1, 2, 5, 4, 1, 3, 0],
[3, 3, 6, 6, 9, 8, 4, 2, 8],
[7, 9, 1, 3, 0, 2, 0, 7, 4],
[6, 7, 9, 3, 0, 2, 1, 9, 2],
[1, 0, 3, 4, 7, 8, 1, 6, 5],
[4, 4, 7, 8, 3, 7, 0, 4, 7]]])
I would like to get 3D chunks of shape 2 × 3 × 3
using a moving window along latter two dimensions (in this case 9 × 9
). The size of the first dimension (I'd call it "depth") is arbitrary. The example of the first chunk would be:
>>> array([
[[np.nan, np.nan, np.nan],
[np.nan, 4, 5],
[np.nan, 9, 2]],
[[np.nan, np.nan, np.nan],
[np.nan, 4, 2],
[np.nan, 1, 5]]])
The second would be:
>>> array([
[[np.nan, np.nan, np.nan],
[4, 5, 1],
[9, 2, 2]],
[[np.nan, np.nan, np.nan],
[4, 2, 0],
[1, 5, 3]]])
And so on...
I later need to apply a more complicated function to these chunks, not a simple average or such, so I would appreciate a new array with them (I guess that is quite memory intensive, is there a different approach? Possibly vectorized? But it's not necessary)
I tried applying np.lib.stride_tricks.as_strided
to my case as in #44305987 and played around with fancy indexing as in #15722324, but did not achieve the desired result.
Thanks!