Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

python - Average every x numbers in NumPy array

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...