[英]python sum all next n values in array at each index
I have an array:我有一个数组:
my_array = [1, 13, 6, 100, 12,23,45] and would like to create a new array that for each index in my_array is the sum of 3 next index values my_array = [1, 13, 6, 100, 12,23,45] 并且想要创建一个新数组,对于 my_array 中的每个索引,它是 3 个下一个索引值的总和
summed_array = [119, 118, 135, 80, 68,45,0] I tried something like np.cumsum but this cumlative values summed_array = [119, 118, 135, 80, 68,45,0] 我尝试了类似 np.cumsum 的东西,但是这个累积值
import numpy as np
sum_value = 0
my_array = [1, 13, 6, 100, 12,23,45]
summed_array = [0, 0, 0, 0, 0,0,0]
print(len(my_array))
for ind,i in enumerate(my_array):
if ind+3< len(my_array):
summed_array[ind] =my_array[ind+1]+my_array[ind+2]+my_array[ind+3]
elif ind+2 < len(my_array):
summed_array[ind] =my_array[ind+1]+my_array[ind+2]
elif ind+1 < len(my_array):
summed_array[ind]=my_array[ind+1]
else:
summed_array[ind] = 0
print(summed_array) ```
With a
being your array: a
你的数组:
>>> c = a.cumsum()
>>> np.concatenate((c[3:], [a.sum()] * 3)) - c
array([119, 118, 135, 80, 68, 45, 0])
You can also do it in list comprehension:您也可以在列表理解中执行此操作:
sum_array = [ sum(my_array[pos+1:pos+4]) for pos in range(len(my_array)) ]
This way there is no need for declaring the sum_array
, as it will always be already created with the correct size.这样就不需要声明
sum_array
,因为它总是已经以正确的大小创建。
Edit: Fixed the 'next 3 values', since I hadn't realised it in the first place.编辑:修复了“下 3 个值”,因为我一开始没有意识到。
If you are trying to minimize the number of additions performed, it might be a good idea to have a pointer so that you add and subtract once for each index instead of adding 3 times.如果您试图最小化执行的加法次数,最好有一个指针,这样您就可以为每个索引加减一次,而不是加 3 次。 You might find a different solution more optimum than this though.
不过,您可能会找到比这更优化的不同解决方案。 If so, please let me know:) Let
a
be your array.如果是这样,请告诉我:) 让
a
成为你的数组。
# Initialize sum array sa with first index
val = sum(a[1:4])
sa = [val]
i = 1
# Get sum for all except last 3 indices
for i in range(1, len(a) - 3):
val = val + a[i + 3] - a[i]
sa.append(val)
# Account for the last 3 indices
while i < len(a):
val -= a[i]
sa.append(val)
i += 1
# sa is the array needed at this point
Please note that empty array would currently return [0].请注意,空数组当前将返回 [0]。 If you intend to return an empty array instead, that would be an edge case that can be handled by an if statement in the beginning
如果您打算返回一个空数组,那将是一个边缘情况,可以在开始时由 if 语句处理
This can be done这可以做到
a = my_array
summed_array= [sum(a[i:i+3]) for i in range(len(a))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.