Skip to content
Advertisement

Python – compute average absolute difference of element and neighbors in NumPy array

I’m looking for a way to calculate the average absolute difference between neighboring elements in a NumPy array. Namely, given an array like

JavaScript

The value for the middle square will be 2.5 (aka (4+3+2+1+1+2+3+4)/8). I know with SciPy’s correlate2d you can compute the average difference, but, as far as I know, not the average absolute difference (i.e. for the example above, correlate2d would give 0 – (-4+-3+-2+-1+1+2+3+4)/8 – not 2.5).

Is there a fast way to do this in Python? I don’t want to iterate over the elements since this will be running for very large arrays many times.

Advertisement

Answer

Why not write it by hand and numba.jit the result?

JavaScript

This takes about 160ms for the 1000 by 1000 array (down from non jited version which takes 10.6s).

For your array I get

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement