Reputation: 33
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!
Upvotes: 3
Views: 981
Reputation: 76683
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)
.
Upvotes: 3
Reputation: 110108
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.
Upvotes: 0
Reputation: 273456
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.
Upvotes: 0