Home > database >  efficient way of substracting along specific dimension in numpy array
efficient way of substracting along specific dimension in numpy array

Time:05-13

I have a NumPy array a of sizes (1000,100,2).

I want to subtract only values from the last dimension iterating along the firsts. In other words:

a[i 1,j,[x1,y1]]-a[i,j,[x0,y0]]

to obtain an array b of size (999,100,2) with the last dimension that contains:

[x1-x0, y1-y0] , etc...

I know how to do that with a for loop, I'm looking for a more efficient "numpyzed" version

CodePudding user response:

Looks like you want np.diff

a = np.random.rand(1000, 100, 2)
b = np.diff(a, axis = 0)
b.shape
Out[]: (999, 100, 2)
  • Related