Home > Mobile >  numba np.diff with axis=0
numba np.diff with axis=0

Time:02-23

While using numba, axis=0 is acceptable parameters for np.sum(), but not with np.diff(). Why is this happening? I'm working with 2D, thus axis specification is needed.

@jit(nopython=True)
def jitsum(y):
    np.sum(y, axis=0)

@jit(nopython=True)
def jitdiff(y): #this one will cause error
    np.diff(y, axis=0)

Error: np_diff_impl() got an unexpected keyword argument 'axis'

A workaround in 2D will be:

@jit(nopython=True)
def jitdiff(y):
    np.diff(y.T).T

CodePudding user response:

np.diff on a 2D array with n=1, axis=1 is just

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

For axis=0:

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

I suspect that the lines above will compile just fine with numba.

CodePudding user response:

def sum(y):
    a=np.sum(y, axis=0)
    b=np.sum(y,axis=1)
    print("Sum along the rows (axis=0):",a)
    print("Sum along the columns (axis=1):",b)

def diff_order1(y):
    a=np.diff(y,axis=0,n=1)
    b=np.diff(y,axis=1,n=1) ## n=1 indicates 1st order difference 
    print("1st order difference along the rows (axis=0):",a)
    print("1st order difference along the columns (axis=1):",b)

def diff_order2(y):
    a=np.diff(y,axis=0,n=2)
    b=np.diff(y,axis=1,n=2) ## n=2 indicates 2nd order difference 
    print("2nd order difference along the rows (axis=0):",a)
    print("2nd order difference along the columns (axis=1):",b)

This function is just another version of solving the problem calling the .diff function twice for order 2 difference

def diff_order2_v2(y):
  a=np.diff(np.diff(y,axis=1),axis=1)
  b=np.diff(np.diff(y,axis=0),axis=0)
  print("2nd order difference along the rows (axis=0):",a)
  print("2nd order difference along the columns (axis=1):",b)

Try running this code, I tried to create functions for sum function and difference function for 1st order and 2nd order difference.

  • Related