2

I have a numpy array X. I need to create another array (say Y) of the same size, which has elements

Y[i] = X[i+1]-X[i-1]

Can I do that without looping over array elements?

6
  • 1
    What's Y[0] (i-1 = -1)? Can you add some small sample input and desired output? Commented Feb 21, 2018 at 18:33
  • docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html Commented Feb 21, 2018 at 18:44
  • @pault, Y[0] and Y[-1] will be handled separately (in fact I just assign fixed values to those two elements). Commented Feb 21, 2018 at 19:06
  • In that case, @Jello's solution should work. Commented Feb 21, 2018 at 19:08
  • 1
    @mamun, diff is nice, but it gives differences between neighbouring elements, while what I need is "leapfrog" difference: not between 2nd and 1st elements (or, say 6th and 5th), but rather between 3rd and 1st ones (7th and 5th, so on). Commented Feb 21, 2018 at 19:09

1 Answer 1

2

You could make new arrays with shifted values and then subtract them from one another. Something like this:

import numpy as np

X  = np.arange(10)
X1 = np.roll(X,-1) #right shift
X2 = np.roll(X,1)  #left shift
Y  = X1 - X2
Sign up to request clarification or add additional context in comments.

1 Comment

this one is perfect. Going to use it if there's no builtin method for that thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.