1

Is there quick way to calculate the difference between two elements in subsequent pairs in python arrays? For example, consider x:

x = np.array([1,5,3,8])

How can I calculate from x the differences between subsequent pairs? My desired output is:

np.array([4,5])

1 Answer 1

4

You can slice in strides of 2 and subtract:

>>> x[1::2] - x[::2]
array([4, 5])

Another solution is to reshape and call np.diff:

>>> np.diff(x.reshape(-1, 2), axis=1).ravel()     
array([4, 5])

A generalised version of this that works for any N * M array would look something like this -

r = np.diff(x.reshape(-1, 2), axis=1).reshape(-1, x.shape[1] // 2)
Sign up to request clarification or add additional context in comments.

4 Comments

Hey thanks for editing my comment to make it more legible. Your answer does provide the solution so thanks! However it does work if you scale it to any arbitrary 2 dimensional array with an even number of rows. For example if I want to to this for a N by M array where M is even. For example: x = np.array([[1,5,3,8],[1,2,3,4]]) with desired output: array([[4,5],[1,1]])
@user7740248 Are you asking or are you telling?
Sorry I posted my response on accident I just edited for a follow up question
@user7740248 Okay. For any N * M array where M is even, this will work: np.diff(x.reshape(-1, 2), axis=1).reshape(-1, x.shape[1] // 2).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.