Search code examples
pythonpython-3.xnumpyaverage

Averaging of every five elements and discarding the sixth element


So i have a Numpy array and i want to average every five elements and discard the sixth element, then average out the next five elements and discard the twelfth element and so on.

I have tried using the library function np.average()but it does not allow me to discard the factor of sixth value.

For Example: I have

Input:

a=[[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]]

Output:

a_avg=[[3,9,15],
       [21,27,33],
       [39,45,51]'

Also is it possible to make it dynamic to the size of array?


Solution

  • IIUC, you can first compute a mask to remove every 6th item.

    Then reshape to have 5 elements in one dimension, compute the mean, and reshape again:

    mask = np.arange(a.shape[1])%6 != 5
    
    a[:, mask].reshape((-1,5)).mean(1).reshape((a.shape[0], -1))
    

    output:

    array([[ 3.,  9., 15.],
           [21., 27., 33.],
           [39., 45., 51.]])
    

    input:

    array([[ 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]])