Serenity
Serenity

Reputation: 36635

python: multiple arithmetic operations for numpy array

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.

Upvotes: 0

Views: 967

Answers (1)

mgilson
mgilson

Reputation: 309861

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).

Upvotes: 2

Related Questions