如何对每 n 个数组值求和并将结果放入新数组中? [复制]

2023-12-01

我有一个很长的数组数字列表,我想将其求和并放入一个新数组中。例如数组:

[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]

会成为:

[6,15,16,6,15,x]

如果我要每 3 求和。

我不知道该怎么做。我认为可能的一个问题是我不知道数组的长度 - 如果有必要,我不介意丢失数据的底部位。

我已经尝试过numpy.reshape功能没有成功:

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

首先将数组切割到正确的长度,然后进行重塑。

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

然后你可以简单地将其相加:

print(np.sum(a_RS,axis=1))
>> [ 6 15 16  9 18]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何对每 n 个数组值求和并将结果放入新数组中? [复制] 的相关文章

随机推荐