开发者

first order differences along a given axis in NumPy array

#co开发者_如何学Gompute 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?


What about:

diff(x)
# array([1, 1, 1, 1, 1, 1, 1, 1, 1])


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


several NumPy builtins will do the job--in particular, diff, ediff1d, and gradient.

i suspect ediff1d is the better choice for the specific cast described in the OP--unlike the other two, ediff1d is acdtually directed/limited to this specific use case--ie, first-order differences along a single axis (or axis of a 1D array).

>>> import numpy as NP
>>> x = NP.random.randint(1, 10, 10)
>>> x
  array([4, 6, 6, 8, 1, 2, 1, 1, 5, 4])

>>> NP.ediff1d(x)
  array([ 2,  0,  2, -7,  1, -1,  0,  4, -1])


Here's a pattern I used a lot for a while:

from itertools import izip

d = [a-b for a,b in izip(x[1:],x[:-1])]


y = [item - x[i - 1] for i, item in enumerate(x[1:])]

If you need to access the index of an item while looping over it, enumerate() is the Pythonic way. Also, a list comprehension is, in this case, more readable.

Moreover, you should never use wild imports (from numpy import *). It will always import more than you need and leads to unnecessary ambiguity. Rather, just import numpy or import what you need, e.g.

from numpy import arange, zeros
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜