[Numpy-discussion] calculating the difference of an array
Emmanuelle Gouillart
emmanuelle.gouillart@normalesup....
Sat Jan 2 04:34:47 CST 2010
Hello Manuel,
the discrete difference of a numpy array can be written in a very
natural way, without loops. Below are two possible ways to do it:
>>> a = np.arange(10)**2
>>> a
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
>>> a[1:] - a[:-1]
array([ 1, 3, 5, 7, 9, 11, 13, 15, 17])
>>> np.diff(a) # another way to calculate the difference
array([ 1, 3, 5, 7, 9, 11, 13, 15, 17])
The error in the example you give is due to the fact that you iterate
over len(ARRAY), which is an integer, hence not an iterable object. You
should write ``for i in range(len(ARRAY))`` instead.
Cheers,
Emmanuelle
On Sat, Jan 02, 2010 at 11:23:13AM +0100, Manuel Wittchen 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?
> Regards and a happy new year,
> Manuel Wittchen
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
More information about the NumPy-Discussion
mailing list