0

I have this code (need to subtract sum of previous elements from current):

arr = np.zeros((N,M,T))
for it in xrange(T):
     sum_arr = np.zeros((M,N))
     for tt in xrange(it): sum_arr += arr[:,:,tt]
     arr[:,:,it] -= sum_arr

Question: Is it way to write this code in pythonic way (prefer one line)? Thx in advance.

2
  • Your indentation in the code seems to be off. Can you please fix it? Commented Oct 10, 2013 at 7:12
  • Yes, sorry - it's fixed. Commented Oct 10, 2013 at 7:19

1 Answer 1

2

I think you can get the sum to be done more efficiently at least:

arr = np.zeros((N, M, T))
for it in xrange(T):
    arr[:,:,it] -= np.sum(arr[:,:,:it], axis=2)

which is almost a 1-liner:

for it in xrange(T): arr[:,:,it] -= np.sum(arr[:,:,:it], axis=2)

I assume that your real data arr is not all zeros -- Otherwise, the sum will be an array of zeros which you then subtract from an array of zeros leaving you with ... and array of zeros (which isn't very interesting).

Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly. I just forgot about np.sum, thanks for clue.

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.