user7740248
user7740248

Reputation: 13

Difference between elements of subsequent pairs in numpy arrays (not numpy.diff)

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])

Upvotes: 1

Views: 1841

Answers (1)

cs95
cs95

Reputation: 402383

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)

Upvotes: 4

Related Questions