0

I have:

in = array([4, 3, 2, 1,
   -3, -2, -1,  0])

How do I subtract the previous element from the next element like this:

out = array([(3-4), (2-3), (1-2),
             (-3-1), (-2-(-3)), (-1-(-2)), (0-1)]
out = array([-1,-1,-1,-4,1,1,-1])
1
  • 1
    out[1:]-out[:-1]. diff does this. Commented Jun 23, 2021 at 0:27

1 Answer 1

2

You can simply use np.diff():

import numpy as np
arr = np.array([4, 3, 2, 1, -3, -2, -1, 0])
print(np.diff(arr)) # [-1 -1 -1 -4  1  1  1]

np.diff() returns an numpy array you just described: the differences between two adjacent elements.

Sign up to request clarification or add additional context in comments.

Comments

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.