[Numpy-discussion] calculating the difference of an array

David Cournapeau cournape at gmail.com
Sat Jan 2 05:31:32 EST 2010

On Sat, Jan 2, 2010 at 7:23 PM, Manuel Wittchen
<manuel.wittchen at gmail.com> wrote:
> Hi,
> I want to calculate the difference between the values of a
> numpy-array. The formula is:
> deltaT = t_(n+1) - t_(n)
> My approach to calculate the difference looks like this:
> for i in len(ARRAY):
>        delta_t[i] = ARRAY[(i+1):] - ARRAY[:(len(ARRAY)-1)]
> print "result:", delta_t
> But I get a TypeError:
> File "./test.py", line 19, in <module>
>    for i in len(ARRAY):
> TypeError: 'int' object is not iterable
> Where is the mistake in the code?

There are several mistakes :)

Assuming ARRAY is a numpy array, len(ARRAY) will return an int. You
would have the same error if ARRAY was any sequence: you should
iterate over range(len(ARRAY)).

Your formula within the loop is not very clear, and does not seem to
match your formula. ARRAY[i+1:] gives you all the items ARRAY[i+1]
until the end, ARRAY[:len(ARRAY)-1] gives you every item ARRAY[j] for
0 <= j < len(ARRAY)-1, that is the whole array.

I think you want:

for i in range(len(ARRAY)-1):
    delta_i[i] = ARRAY[i+1] - ARRAY[i]

Also, using numpy efficiently requires to use vectorization, so actually:

delta_t = ARRAY[1:] - ARRAY[:-1]

gives you a more efficient version.

But really, you should use diff, which implements what you want:

import numpy as np
delta_t = np.diff(ARRAY)



More information about the NumPy-Discussion mailing list