Fast way to take average of every N rows in a .npy array

后端 未结 3 982
清酒与你
清酒与你 2021-01-05 18:32

I have a very large masked NumPy array (originalArray) with many rows and two columns. I want take the average of every two rows in originalArray

3条回答
  •  甜味超标
    2021-01-05 19:36

    Your problem (average of every two rows with two columns):

    >>> a = np.reshape(np.arange(12),(6,2))
    >>> a
    array([[ 0,  1],
           [ 2,  3],
           [ 4,  5],
           [ 6,  7],
           [ 8,  9],
           [10, 11]])
    >>> a.transpose().reshape(-1,2).mean(1).reshape(2,-1).transpose()
    array([[  1.,   2.],
           [  5.,   6.],
           [  9.,  10.]])
    

    Other dimensions (average of every four rows with three columns):

    >>> a = np.reshape(np.arange(24),(8,3))
    >>> a
    array([[ 0,  1,  2],
           [ 3,  4,  5],
           [ 6,  7,  8],
           [ 9, 10, 11],
           [12, 13, 14],
           [15, 16, 17],
           [18, 19, 20],
           [21, 22, 23]])
    >>> a.transpose().reshape(-1,4).mean(1).reshape(3,-1).transpose()
    array([[  4.5,   5.5,   6.5],
           [ 16.5,  17.5,  18.5]])
    

    General formula for taking the average of r rows for a 2D array a with c columns:

    a.transpose().reshape(-1,r).mean(1).reshape(c,-1).transpose()
    

提交回复
热议问题