将NumPy数组中的每x个数字取平均值 [英] Average every x numbers in NumPy array

查看:543
本文介绍了将NumPy数组中的每x个数字取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个由100个随机数组成的数组,称为random_array.我需要创建一个数组,该数组在random_array中平均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.

因此,如果我有x = 7,则我的代码将找到前7个数字的平均值并将其存储在新数组中,然后存储在下一个7,然后存储在下一个7 ...

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

我目前有这个,但我想知道如何将其向量化或使用某些python方法:

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

推荐答案

这是使用样品运行-

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

为了提高性能,我们可以使用np.add.reduceat-

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

这篇关于将NumPy数组中的每x个数字取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆