简体   繁体   中英

Cumulative sum of a numpy array and store each value into a new array

I have a numpy array fs by reading from a *.csv file. It's size is (606,) and the data type is float64.

Example a my raw data

i   M(i)    dM(i)
1   0.0012  0.00013
2           0.00015
3           0.00016
4           0.00018

Now every element of my array should be calculated like this: M(i) = M(i-1) + dM(i-1)*t .

t is a constant factor of 10.

M(2) would be M(2) = M(1) + dM(1)*t = 0.0012 + 0.00013*10 = 0.0025 M(3) would be M(3) = M(2) + dM(2)*t = 0.0025 + 0.00015*10 = 0.004

I calculated some values manually.

i   M(i)    dM(i)
1   0.0012  0.00013
2   0.0025  0.00015
3   0.004   0.00016
4   0.0056  0.00018

My idea was simply to write a for loop for every item in the array, but the calculations seem to be wrong. fs is the array and t is a certain time interval. t is constant and has a value of 10

#   Ms(t)
def mass(t, fs):
    M_st = 0
    for i in fs
        M_st = M_st + i*t
    return M_st
sum = mass(10,fs)

Iterate through the file line by line, and append the current line's value plus the value of the previous element in the result array. I'm not an expert with numpy arrays, but something like this would work for a standard list

def create_sum_array(input_arr, length): 
   temp_arr = []
   for i in range(length):
     if(temp_arr = []):
       temp_arr.append(input_arr[i])
     else:
       temp_arr.append(temp_arr[i-1] + input_arr[i])
   return temp_arr

it's not the most elegant solution, but something like this would work:

import numpy as np
array = np.array([1, 2, 3, 4, 5, 6])
array2 = np.zeros(len(array))
for i in range(len(array)):
    if i == 0:
        array2[i] = array[i]
        
    array2[i] = np.sum(array[:i+1]) 
print(array2)

one elegant solution would be

m = arr[0]
temp = np.tril(np.ones([m, m]))

new_arr = temp @ arr

Use the built in function cumsum for it ( a is your array):

a.cumsum()
#[ 1  4  8 13 19 26]

UPDATE : Based on OP's edit on post ( t is scalar and M and dM are arrays. Note that python indexing is zero-based and NOT one-based):

M(0) + (dM*t).cumsum()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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