简体   繁体   中英

How can I replace nan values in a 2d ndarray with values of the closest non nan non zero value

2D array has regularly distributed values, so the task is replace each NaN or 0 between values with the value of the closest element. If the position of element is strictly middle, so the least of two values will be taken for example.

The input array could be plotted as a square grid with values and the task could be treated as regridding to better resolution, but without any interpolation.

This solution here seems not to be appropriate for 2D arrays. Is there a build in function in numpy or scipy for this task?

Let it be a zero array with each 6th element - a random int value:

a = np.zeros((121,121),dtype='float32')
a[0::6,0::6] = np.random.randint(1,100,(21,21))

And let make two matrices of indices of the a:

ind1, ind2 = np.meshgrid(range(0,a.shape[0],1),range(0,a.shape[1],1))

So, we get indices of non zero nodes:

i = np.argwhere(a)

And here's the solution for the task that gives a grid filled up with nearest values:

def regridding(ind1,ind2,i, a):
    args = np.sqrt((ind2-i[:,0])**2 + (ind1-i[:,1])**2).argmin()
    b = a[i[args][0]][i[args][1]]
    a[ind2][ind1] = b

func = np.vectorize(regridding, excluded=['i', 'a'])
func(ind1=ind1, ind2=ind2, i=i, a=a)

You can save it to txt and check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM