numpy 如何计算Numy数组中每4个元素的平均值

wh6knrhe  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(208)

Sample_List=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])

Required to take the average of every 4 
like 1,2,3,4 average is 2.5
followed by 5,6,7,8 is 6.5
followed by 9,10,11,12 is 10.5
followed by 13,14,15,16 is 14,5

Exexted输出:

[2.5, 6.5, 10.5, 14.5]

到目前为止,我试着参考这个问题Average of each consecutive segment in a list
Calculate the sum of every 5 elements in a python array

cngwdvgl

cngwdvgl1#

使用reshape。在下面的示例中,RESHAPE(-1,4)表示每行4个元素

import numpy as np

sample_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

print(np.mean(sample_list.reshape(-1, 4), axis=1))

输出

[2.5, 6.5, 10.5, 14.5]
zhte4eai

zhte4eai2#

有多种方法可以做到这一点。考虑到sample_list如下所示

sample_list = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])

[Out]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])

将在下面留下两个选项,这两个选项将允许计算数值数组中每4个元素的平均值。

选项1

newlist = [sum(sample_list[i:i+4])/4 for i in range(0, len(sample_list), 4)]

[Out]: [2.5, 6.5, 10.5, 14.5]

选项2

使用numpy.mean

newlist = [np.mean(sample_list[i:i+4]) for i in range(0, len(sample_list), 4)]

[Out]: [2.5, 6.5, 10.5, 14.5]

相关问题