I have a 3D matrix where some of the slices (axis 1 & 2) sometimes have NaNs, sometimes are filled with NaNs, and sometimes are filled with numbers. I would like to interpolate the NaNs by applying a "Nearest Neighbor" interpolation on the axis 0. This way if for example arr[0,0,0] is a NaN, my algorithm will search on arr[1:-1,0,0] the nearest value and interpolate it to replace arr[0,0,0] by a number.
So far this is how I intended to do:
import numpy as np
from scipy import interpolate
arr = np.empty((4,4,5))
arr[:] = np.nan
arr[0] = np.random.random()
arr[3] = np.random.random()
arr[0,0:2,0:2] = np.nan
def gap_filling(vect, interpolation):
time = np.arange(0, np.shape(vect)[0])
mask = np.isfinite(vect)
f = interpolate.interp1d(time[mask], vect[mask],
kind=interpolation, bounds_error=False)
vect_filled = np.copy(vect)
vect_filled[np.isnan(vect)] = f(time[np.isnan(vect)])
return vect_filled
result = np.apply_along_axis(gap_filling, 0, arr, interpolation)
However I have an error due to the fact that if I have a vector with only NaNs (arr[2,0,:] for example) the function does not work. If I only have isolated NaNs in my vector, it works. I went on several forum question (Get interpolated 2D matrix by interpolating layers of 3D matrix in Matlab, Interpolate a 3D array in Python, interpolate 3D volume with numpy and or scipy) but none of the accepted answers worked for my kind of array.
Is there a better way to do that ? In the end I would like my array "result" to be filled with values.