python求数组平均值numpy_将NumPy数组中的每x个数字取平均值

Let's say I have an array of 100 random numbers called random_array. I need to create an array that averages x numbers in random_array and stores them.

So if I had x = 7, then my code finds the average of the first 7 numbers and stores them in my new array, then next 7, then next 7...

I currently have this but I'm wondering how I can vectorize it or use some python method:

random_array = np.random.randint(100, size=(100, 1))

count = 0

total = 0

new_array = []

for item in random_array:

if (count == 7):

new_array.append(total/7)

count = 0

total = 0

else:

count = count + 1

total = total + item

print new_array

解决方案

Here's an approach with ID-based summing/averaging using np.bincount -

ids = np.arange(len(random_array))//7

out = np.bincount(ids,random_array)/np.bincount(ids)

Sample run -

In [140]: random_array

Out[140]:

array([89, 66, 29, 25, 36, 25, 30, 58, 64, 19, 25, 63, 76, 74, 44, 73, 94,

88, 83, 88, 17, 91, 69, 65, 32, 73, 91, 20, 20, 14, 52, 65, 21, 58,

14, 30, 26, 82, 61, 87, 24, 67, 83, 93, 57, 30, 81, 48, 84, 83, 59,

19, 95, 55, 86, 57, 59, 77, 92, 44, 40, 29, 37, 42, 33, 89, 37, 57,

18, 17, 85, 47, 19, 95, 96, 40, 13, 64, 18, 79, 95, 26, 31, 70, 35,

65, 52, 93, 46, 63, 86, 77, 87, 48, 88, 62, 68, 82, 49, 86])

In [141]: ids = np.arange(len(random_array))//7

In [142]: np.bincount(ids,random_array)/np.bincount(ids)

Out[142]:

array([ 42.85714286, 54.14285714, 69.57142857, 63. ,

34.85714286, 53.85714286, 68. , 64.85714286,

54. , 41.85714286, 56.42857143, 54.71428571,

62.85714286, 73.14285714, 67.5 ])

In [143]: random_array[:7].mean() # Verify output[0]

Out[143]: 42.857142857142854

In [144]: random_array[7:14].mean() # Verify output[1]

Out[144]: 54.142857142857146

In [145]: random_array[98:].mean() # Verify output[-1]

Out[145]: 67.5

For performance, we can replace np.bincount(ids,random_array) with an alternative one using np.add.reduceat -

np.add.reduceat(random_array,range(0,len(random_array),7))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值