[英]2d interpolation with NaN values in python
I have a 2d matrix (1800*600) with many NaN values. 我有一个带有许多NaN值的二维矩阵(1800 * 600)。
I would like to conduct a 2d interpolation, which is very simple in matlab. 我想进行二维插值,这在matlab中非常简单。 But if scipy.interpolate.inter2d
is used, the result is a NaN
matrix. 但是,如果使用scipy.interpolate.inter2d
,则结果为NaN
矩阵。 I know the NaN
values could be filled using scipy.interpolate.griddata
, but I don't want to fulfill the Nan
. 我知道可以使用scipy.interpolate.griddata
填充NaN
值,但我不想满足Nan
。 What other functions can I use to conduct a 2d interpolation? 我还可以使用其他哪些功能进行二维插值?
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. 使用inter2d
一种解决方法是执行两个插值:一个在填充的数据上(用任意值替换NaN),另一个用于跟踪未定义的区域。 It is then possible to re-assign NaN value to these areas: 然后可以将NaN值重新分配给以下区域:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.