Loop to perform operation on i+1 in numpy array

769 views arrays

I have a 3x56075 numpy array, I'd like to take the 3 numbers in each row, minus them from the next row and store those values in another array.

something like

for i in array:
    a = i - i+1

I know this is very wrong, but at least this gives the idea of what I want.

Obviously i+1 will just result in the value + 1 and then all I have is a = 1,1,1

When I say i+1 I mean the next in line.

So for example:

input = np.array([[4,4,5], [2,3,1],[1,2,0]])
output =  np.array([2,1,4],[1,1,1]) etc....

What would be the best way to do this iteratively on thousands of rows?

answered question

1 Answer


IIUC, instead of looping, you can just shift your arrays 1 up using np.roll, subtract that from your original input, and take all the resulting arrays except the last (because there will be nothing to subtract from the last array):

>>> inp = np.array([[4,4,5], [2,3,1],[1,2,0]])
>>> inp
array([[4, 4, 5],
       [2, 3, 1],
       [1, 2, 0]])
>>> (inp - np.roll(inp,-1,axis=0))[:-1]
array([[2, 1, 4],
       [1, 1, 1]])

posted this

Have an answer?


Please login first before posting an answer.