1

I have a 3D array that I want to interpolate the np.nan values along the z dimension, and I just want the changes to modify my existing array. However, the changes seems not to be working. I have a test array with dimension (3,3,3) with nan values. I am accessing the z dimension and perform interpolation. I would like to have is that nan values will be replaced by interpolated values along the z dimension.

def arr_interp(array):
    arrN=np.array(array)
    ix=-np.isnan(arrN)
    idxTrue=ix.nonzero()[0]
    valueTrue=arrN[-np.isnan(arrN)]
    countFalse=np.isnan(arrN).ravel().nonzero()[0]
    arrN[np.isnan(arrN)]=np.interp(countFalse,idxTrue,valueTrue)
    # I got this function from another forum


In [177]:arrStack
Out[178]: 
array([[[ 0.59016759,         nan,  0.88641936],
        [ 0.94884139,         nan,  0.89443098],
        [ 0.7730535 ,         nan,  0.86262287]],

       [[ 0.106567  ,         nan,  0.83757824],
        [ 0.21794018,         nan,  0.66128902],
        [ 0.21961069,         nan,  0.28654693]],

       [[ 0.26142901,         nan,  0.95653887],
        [ 0.19616204,  0.45      ,  0.61531475],
        [ 0.78262652,  0.76      ,  0.47786104]]])

In [181]: arrStack[0][0]
Out[182]: array([ 0.59016759,         nan,  0.88641936])

In [183]: arr_interp(arrStack[0][0])

In [184]: arrStack
Out[184]: 
array([[[ 0.59016759,         nan,  0.88641936],
        [ 0.94884139,         nan,  0.89443098],
        [ 0.7730535 ,         nan,  0.86262287]],

       [[ 0.106567  ,         nan,  0.83757824],
        [ 0.21794018,         nan,  0.66128902],
        [ 0.21961069,         nan,  0.28654693]],

       [[ 0.26142901,         nan,  0.95653887],
        [ 0.19616204,  0.45      ,  0.61531475],
        [ 0.78262652,  0.76      ,  0.47786104]]])
0

The problem is in your second line of code

arrN=np.array(array)

What this does is create a copy of your input array since the standard behaviour is np.array(x, copy=True). This way you are interpolating the copy instead of the original array.

If you want to modify the existing array in place just change it to:

arrN=np.array(array, copy=False)

This way arrN points to the original input array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.