每五个元素取平均并舍弃第六个元素

Averaging of every five elements and discarding the sixth element

所以我有一个 Numpy 数组,我想对每五个元素进行平均并丢弃第六个元素,然后对接下来的五个元素进行平均并丢弃第十二个元素等等。

我试过使用库函数 np.average() 但它不允许我丢弃第六个值的因子。

例如:我有

输入:

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]]

输出:

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

是否可以根据数组的大小使其动态变化?

IIUC,你可以先计算一个掩码,每隔 6 项删除一次。

然后整形为一维有 5 个元素,计算平均值,然后再次整形:

mask = np.arange(a.shape[1])%6 != 5

a[:, mask].reshape((-1,5)).mean(1).reshape((a.shape[0], -1))

输出:

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

输入:

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]])