Reshaping a multidimensional array in a rolling/moving window manner and plot

Viewed 30

I have a multi-dimension array generated using NumPy.

array = np.random.rand(63, 4, 4)

Now I want to generate images using the imshow() function from matplotlib, using a rolling/moving window manner grouping 4 entries at a time.

for example, I can generate the first image using the following code,

plt.imshow(array[0])
plt.show()

What I mean by rolling/moving window manner is something which will be cleared using the following example. For array[0] case,

row_labels = ['rice', 'oil', 'egg', 'veggies']
column_labels = ['day1', 'day2', 'day3', 'day4']


df1 = pd.DataFrame(array[0], columns=column_labels, index=row_labels)
df1

Output

            day1      day2        day3        day4
rice    0.178611    0.988470    0.478903    0.549904
oil     0.620687    0.873206    0.480170    0.816815
egg     0.139812    0.726773    0.007565    0.909480
veggies 0.038050    0.532996    0.577851    0.184854

For array[1] case,

row_labels = ['rice', 'oil', 'egg', 'veggies']
column_labels = ['day5', 'day6', 'day7', 'day8']


df2 = pd.DataFrame(array[1], columns=column_labels, index=row_labels)
df2

Output

           day5       day6        day7        day8
rice    0.495291    0.970483    0.061865    0.503121
oil     0.861100    0.424734    0.506361    0.153064
egg     0.414194    0.326667    0.882147    0.940914
veggies 0.478632    0.455433    0.527137    0.116123

The way I want to generate the images is the first image will have [day1,day2,day3,day4] then the second image will have [day2,day3,day4,day5] then the following image will have [day3,day4,day5,day6] and so op until the end.....

even I can get another multidimensional array reshaped like the rolling window manner I wrote will help me; after that, I can loop through to produce the images.

Please help me with this!

1 Answers

numpy.lib.stride_tricks.sliding_window_view can do the trick for you here.

import numpy as np

array = np.random.rand(63, 4, 4)
# I've set the window size to five here to illustrate the shapes. Change
# it back to four to get the desired result.
size = 5
# Get the windowed view of the original array (this may consume a lot of
# memory if your array or window size is large).
windowed = np.lib.stride_tricks.sliding_window_view(array, size, axis=0)
windowed.shape  # (60, 4, 4, 5)
# Compute the average over the window.
moving_avg = windowed.mean(axis=-1)
# Let's check that the windowed avg agrees with our intuition.
np.testing.assert_allclose(moving_avg[0], array[:size].mean(axis=0))
Related