Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Subtract current rows second element from the next rows first element in numpy

I have 6x2 numpy array. I want to subtract current rows second element from the next rows first element and get the new column. Currently i'm using for loop to do that. Ex:

from numpy import array
a = array([[1,3],
           [2,5],
           [6,7],
           [8,9],
           [5,6],
           [6,9]])
k = []
for i in range(a.shape[0]-1):
    k.append(a[i][1]-a[i+1][0])
array(k)

Output : [1, -1, -1, 4, 0]

How can I get the same output using numpy?

Upvotes: 0

Views: 1054

Answers (1)

Divakar
Divakar

Reputation: 221584

Slice and subtract -

a[1:,0] - a[:-1,1]

Sample run -

In [303]: a
Out[303]: 
array([[1, 3],
       [2, 5],
       [6, 7],
       [8, 9],
       [5, 6],
       [6, 9]])

In [304]: a[1:,0] - a[:-1,1]
Out[304]: array([-1,  1,  1, -4,  0])

Since, we have two columns only, another way/trick would be to use differentiaton on flattened version and then step into every other element starting from the second element -

In [308]: np.diff(a.ravel())[1::2]
Out[308]: array([-1,  1,  1, -4,  0])

Upvotes: 1

Related Questions