如何对每n个数组值求和并将结果放入新数组中? [英] How can I sum every n array values and place the result into a new array?
本文介绍了如何对每n个数组值求和并将结果放入新数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长的数组编号列表,我想对它们进行求和并放入一个新数组中.例如数组:
I have a very long list of array numbers I would like to sum and place into a new array. For example the array:
[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
将成为:
[6,15,16,6,15,x]
如果我想每3加总一次.
if I was to sum every 3.
我不知道该怎么做.我认为可能的一个问题是我不知道我的数组的长度-如果有必要,我不介意丢失数据的最低位.
I cannot figure out how to go about it. I think possibly one problem is I do not know the length of my array - I do not mind losing the bottom bit of data if necessary.
我尝试了numpy.reshape
函数,但没有成功:
I have tried the numpy.reshape
function with no success:
x_ave = numpy.mean(x.reshape(-1,5), axis=1)
ret = umr_sum(arr, axis, dtype, out, keepdims)
我得到一个错误:
TypeError: cannot perform reduce with flexible type
推荐答案
首先将数组剪切为正确的长度,然后进行整形.
Cut the array to the correct length first then do a reshape.
import numpy as np
N = 3
a = np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8])
# first cut it so that lenght of a % N is zero
rest = a.shape[0]%N
a = a[:-rest]
assert a.shape[0]%N == 0
# do the reshape
a_RS = a.reshape(-1,N)
print(a_RS)
>> [[1 2 3]
[4 5 6]
[7 8 1]
[2 3 4]
[5 6 7]]
然后您可以简单地将其添加:
then you can simply add it up:
print(np.sum(a_RS,axis=1))
>> [ 6 15 16 9 18]
这篇关于如何对每n个数组值求和并将结果放入新数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文