ADDonut
ADDonut

Reputation: 45

Subtract first and last element (wrap around) in numpy diff

I have a large 100000,6 array and would like to find the diffence to the each element in the vector. np.diff is almost exactly what I need but also want it to wrap around and it also finds the differnce in the first and last element.

Toy model:

array=np.array([[0,2,4],[0,3,6]])
np.diff(array,axis=1)

gives [[2,2],[3,3]] would like to have [[2,2,-4],[3,3,-6]] or [[-4,2,2],[-6,3,3]]

Is there a built in way in numpy to do this?

Upvotes: 4

Views: 814

Answers (1)

mozway
mozway

Reputation: 260965

You can use numpy.roll:

np.roll(array, -1, axis=1)-array

Output:

array([[ 2,  2, -4],
       [ 3,  3, -6]])

Upvotes: 3

Related Questions