LEO
LEO

Reputation: 63

2d interpolation with NaN values in python

I have a 2d matrix (1800*600) with many NaN values.
enter image description here
I would like to conduct a 2d interpolation, which is very simple in matlab. But if scipy.interpolate.inter2d is used, the result is a NaN matrix. I know the NaN values could be filled using scipy.interpolate.griddata, but I don't want to fulfill the Nan. What other functions can I use to conduct a 2d interpolation?

Upvotes: 1

Views: 5844

Answers (1)

xdze2
xdze2

Reputation: 4151

A workaround using inter2d is to perform two interpolations: one on the filled data (replace the NaNs with an arbitrary value) and one to keep track of the undefined areas. It is then possible to re-assign NaN value to these areas:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from scipy.interpolate import interp2d

# Generate some test data:
x = np.linspace(-2, 2, 40)
y = np.linspace(-2, 2, 41)
xx, yy = np.meshgrid(x, y)

z = xx**2+yy**2
z[ xx**2+yy**2<1 ] = np.nan

# Interpolation functions:
nan_map = np.zeros_like( z )
nan_map[ np.isnan(z) ] = 1

filled_z = z.copy()
filled_z[ np.isnan(z) ] = 0

f = interp2d(x, y, filled_z, kind='linear')
f_nan = interp2d(x, y, nan_map, kind='linear')     

# Interpolation on new points:
xnew = np.linspace(-2, 2, 20)
ynew = np.linspace(-2, 2, 21)

z_new = f(xnew, ynew)
nan_new = f_nan( xnew, ynew )
z_new[ nan_new>0.5 ] = np.nan

plt.pcolor(xnew, ynew, z_new);

Upvotes: 3

Related Questions