Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first order differences along a given axis in NumPy array

#compute first differences of 1d array
from numpy import *

x = arange(10)
y = zeros(len(x))

for i in range(1,len(x)):
    y[i] = x[i] - x[i-1]
print y

The above code works but there must be at least one easy, pythonesque way to do this without having to use a for loop. Any suggestions?

like image 698
Dick Eshelman Avatar asked Jan 29 '11 04:01

Dick Eshelman


2 Answers

What about:

diff(x)
# array([1, 1, 1, 1, 1, 1, 1, 1, 1])
like image 130
Marcin Avatar answered Oct 20 '22 01:10

Marcin


Yes, this exactly the kind of loop numpy elementwise operations is designed for. You just need to learn to take the right slices of the arrays.

x = numpy.arange(10)
y = numpy.zeros(x.shape)

y[1:] = x[1:] - x[:-1]

print y
like image 32
AFoglia Avatar answered Oct 20 '22 01:10

AFoglia