# How to average every 50 values inside a larger matrix in Python

## Issue

I have an array of 7000 images and those images are of size 224x224x3. Therefore the entire matrix shape is `(7000, 224, 224, 3)`. What I want to do is select every 50 images and calculate their mean obtaining 1 frame averaged out of 50, so in total I’d have an array of size `(140, 224, 224, 3)`. A minimal reproducible example:

``````import numpy as np

array = np.random.randint(255, size=(7000, 224, 224, 3))
mean_frame = np.mean(([frame for frame in array]), axis=0)
``````

This is the closest I could get, it’ll give me a single image of `(224, 224, 3)` because it averaged all images, but I’d like to grab every 50 frames instead. Basically, I’d like to know how can I select every 50 frames from this larger array of images and average them to obtain the same average frame I am trying to?

## Solution

One way you can do it is to reshape the array so that it becomes `140 x 50 x 224 x 224 x 3` then take the average along the second axis:

``````mean_frame = np.mean(np.reshape(array, (140, 50, 224, 224, 3)), axis=1)
``````

By reshaping your array this way, each element in the first dimension will have access to a batch of 50 images, and so averaging along the second dimension will average 50 images for each element along the first dimension.