Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Average consective nth row in numpy

I have a 3D numpy array.

x=np.random.randint(low=0,high=10,size=(100,64,1000))

I want to average every 4th row, for example first 4, then 4-8, 8-12 and so on.
I tried the following way

x =np.split(x,len(x)/4)
np.mean(np.stack(x),1)

I am bit confused if its the correct way? Or if there is a better way. Also how to do if first dimension is not completely divisible by 4.
For example, I can do this way

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x =np.array_split(x,len(x)/4)
np.stack([np.mean(i,0) for i in x],0)

Thanks

EDIT:
Here is my use case.
This is sensor data, where 100 is the number of time data been collected (trials), 64 is the number of channels of sensor and 1000 is sensor signal (length). I want sensor signal to be average for first 4 trials, then next 4 trials and so on.

>Solution :

Using reshape and mean

Try this with a reshape and then mean over the specific axis –

x = np.random.randint(low=0,high=10,size=(100,64,1000))

#Reshape to (4, 25, 65, 1000) and then reduce 0th axis with a mean
x = x.reshape(4,-1,64,1000).mean(0)
x.shape
(25, 64, 1000)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading