Home > Back-end >  Index based subtraction , substituing element with the result of such subtraction at element index
Index based subtraction , substituing element with the result of such subtraction at element index

Time:06-11

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

CodePudding user response:

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