0

I am trying to make the transition from excel to python, but run in some troubles, with summing every element within an one dimensional array.

In excel this can be easily done, as in the attached image.

From excel I can clearly see the mathematical pattern for achieving this. My approach was to create a for loop, by indexing the array A.

This is my code:

import numpy as np

A = np.array([0.520094,0.850895E-1,-0.108374e1])

B = np.array([0]) #initialize array
B[0] = A[0] 

A is equivalent to column A in excel & similarly B

Using a for loop to sum every element/row:

for i in range(len(A)):
        i = i+1
        B.append([B[i-1]+A[i]])
    print(B)

Excel equivalent for summing column A at every row

This strategy doesn't work and keep getting erros. Any suggestion as to how I could make this work or is there a more elegant way of doing this?

1 Answer 1

2

Just use np.cumsum:

import numpy as np

A = np.array([0.520094,0.850895E-1,-0.108374e1])

cumsum = np.cumsum(A)
print(cumsum)

Output:

[ 0.520094   0.6051835 -0.4785565]

A manual approach would look like this:

A = np.array([0.520094,0.850895E-1,-0.108374e1])
B = [] # Create B as a list and not a numpy array, because it's faster to append

for i in range(len(A)):
    cumulated = A[i]
    if i > 0:
        cumulated += B[i-1]
    B.append(cumulated)

B = np.array(B) # Convert B from list to a numpy array
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your input. That would be easier, but I would like to use a loop to do the summation. As I would like to perform a function on each of the sum answers for the elements. I was hoping to do a cumulative summation. Which is probably a more descriptive title
I edited my post with a manual version using explicit loops. It will take longer than the numpy version though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.