Index based subtraction , substituing element with the result of such subtraction at element index

Issue

I have the following numpy array.

array([[40, 2092, 7, 1310],
       [38, 1966, 2, 879],
       [30, 1944, 1, 868]])

And i want to subtract the first value of the first ‘list’ minus the first value ‘list’ of the second list and so on. Is worth noting the element index, is to become the value of such subtraction. Any ideas on how i could approach this issue?

Wanted array:

array([[2, 126, 5, 431],
       [8, 22, 1, 11]])

Solution

Slice directly and subtract:

>>> a = np.array([[40, 2092, 7, 1310],
...        [38, 1966, 2, 879],
...        [30, 1944, 1, 868]])
>>> a[:-1] - a[1:]
array([[  2, 126,   5, 431],
       [  8,  22,   1,  11]])

Or use np.diff:

>>> -np.diff(a, axis=0)
array([[  2, 126,   5, 431],
       [  8,  22,   1,  11]])

Answered By – Mechanic Pig

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published