简体   繁体   English

python在每个索引处总结数组中的所有先前值

[英]python sum all previous values in array at each index

I have an array:我有一个数组:

my_array = [1, 4, 1, 13, 9]

and would like to create a new array that for each index in my_array is the sum of all the previous index values并想创建一个新数组,该数组对于 my_array 中的每个索引是所有先前索引值的总和

summed_array = [0, 1, 5, 6, 19]

I tried something like我试过类似的东西

for ind,i in enumerate(my_array):
    print i, my_array[ind-1]

but can't figure out how to get the summation over all previous values.但无法弄清楚如何获得所有先前值的总和。

>>> from numpy import cumsum, ones
>>> a = ones(10)
>>> print(cumsum(a))
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

A pure Python implementation:一个纯 Python 实现:

def cumilative_sum(lst):
    total, result = 0, []
    for ele in lst:
        result.append(total)
        total += ele
    return result

itertools.accumulate would work the same as numpy.cumsum : itertools.accumulate工作方式与numpy.cumsum相同:

from operator import add
from itertools import accumulate
from operator import add

def cum_sum(l):
   return accumulate(l, add)

In [22]: list(cum_sum(my_array))
Out[22]: [1, 5, 6, 19, 28]

which will match cumsum exactly.这将完全匹配 cumsum。

If you want to ignore the last element:如果要忽略最后一个元素:

from operator import add
from itertools import islice, accumulate


def cum_sum(l, take):
   return accumulate(islice(my_array, 0, len(l)-take), add)

In [16]: list(cum_sum(my_array, 1))
Out[16]: [1, 5, 6, 19]

To exactly match your output including the 0 and to work in python2 or 3 you can create a generator function:要完全匹配包括 0 在内的输出并在 python2 或 3 中工作,您可以创建一个生成器函数:

my_array = [1, 4, 1, 13, 9]

def cum_sum(l):
    sm = 0
    for ele in l:
        yield sm
        sm += ele

Output:输出:

In [5]: my_array = [1, 4, 1, 13, 9]

In [6]: list(cum_sum(my_array))
Out[6]: [0, 1, 5, 6, 19]

Hereby another variant of the above using list comperhension:在此使用列表理解的上述另一种变体:

[sum(my_array[0:i[0]]) for i in enumerate(my_array)]

enumerate is handy to use since it creates tuples containing the index and value at that index enumerate 使用起来很方便,因为它创建了包含该索引处的索引和值的元组

np.cumsum(my_array) - my_array

np.cumsum returns an array of cumulative sums, with each sum going up to and including the corresponding element in the input array. np.cumsum返回一个累积总和数组,每个总和达到并包括输入数组中的相应元素。 You want to exclude the corresponding elements from the sum, so just subtract them out.您想从总和中排除相应的元素,因此只需将它们减去即可。

Here is a concise and understandable implementation:这是一个简洁易懂的实现:

sum = 0

my_array = [1, 4, 1, 13, 9]
summed_array = [0, 0, 0, 0, 0]

for ind,i in enumerate(my_array):
    summed_array[ind] = sum
    sum += my_array[ind]

The code basically starts assigning sum with 0 and putting it into the first index of summed_array , and then it adds each respective index of my_array to sum.代码基本上开始用 0 分配 sum 并将其放入summed_array的第一个索引中,然后将my_array每个相应索引添加到 sum。 Then, it comes back to the for loop and assigns each index of summed_array with the previous sum .然后,它返回到for循环并将summed_array每个索引分配给前一个sum

The output would be:输出将是:

>>> summed_array

[0, 1, 5, 6, 19]

...which is the final expected sums. ...这是最终的预期金额。

EDIT: Thanks @IanAuld, he suggested another method to do it without enumeration and initializing values to 0:编辑:谢谢@IanAuld,他建议了另一种方法来做到这一点,无需枚举并将值初始化为0:

sum = 0

my_array = [1, 4, 1, 13, 9]
summed_array = []

for i in my_array:
    summed_array += [sum]
    sum += i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM