首页 > 解决方案 > Cummulative addition in a loop

问题描述

I am trying to cummatively add a value to the previous value and each time, store the value in an array.

This code is just part of a larger project. For simplicity i am going to define my variables as follows:

ele_ini = [12]
smb = [2, 5, 7, 8, 9, 10]

val = ele_ini
for i in range(len(smb)):
     val += smb[i]
     print(val)
     elevation_smb.append(val)

Problem

Each time, the previous value stored in elevation_smb is replaced by the current value such that the result i obtain is:

elevation_smb = [22, 22, 22, 22, 22, 22]

The result i am expecting however is

elevation_smb = [14, 19, 26, 34, 43, 53]

NOTE: ele_ini is a vector with n elements. I am only using 1 element just for simplicity.

标签: pythonpandasloopsnumpy

解决方案


不要使用循环,因为慢。更好的是下面的快速矢量化解决方案。

我认为需要并numpy.cumsum添加向量ele_ini2d numpy array

ele_ini = [12, 10, 1, 0]
smb = [2, 5, 7, 8, 9, 10]

elevation_smb  = np.cumsum(np.array(smb)) + np.array(ele_ini)[:, None]
print (elevation_smb)
[[14 19 26 34 43 53]
 [12 17 24 32 41 51]
 [ 3  8 15 23 32 42]
 [ 2  7 14 22 31 41]]

推荐阅读