views:

73

answers:

3

What is the best way to touch two following values in an numpy array?

example:

npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
    print npdata[i] - npdata[i+1]

this looks really messed up and additionally needs exception code for the last iteration of the loop. any ideas?

Thanks!

A: 

How about range(len(npdata) - 1) ?

Here's code (using a simple array, but it doesn't matter):

>>> ar = [1, 2, 3, 4, 5]
>>> for i in range(len(ar) - 1):
...   print ar[i] + ar[i + 1]
... 
3
5
7
9

As you can see it successfully prints the sums of all consecutive pairs in the array, without any exceptions for the last iteration.

Eli Bendersky
A: 

You can use ediff1d to get differences of consecutive elements. More generally, a[1:] - a[:-1] will give the differences of consecutive elements and can be used with other operators as well.

interjay
+1  A: 

numpy provides a function diff for this basic use case

>>> import numpy
>>> x = numpy.array([1, 2, 4, 7, 0])
>>> numpy.diff(x)
array([ 1,  2,  3, -7])

Your snippet computes something closer to -numpy.diff(x).

Mike Graham
+1 this is a good answer
Eli Bendersky