[英]Interpolate dataArray missing data using xarray
I am using xarray/rasterio to do some operations on a set of GeoTiff files.我正在使用 xarray/rasterio 对一组 GeoTiff 文件进行一些操作。 The data that I am dealing with contain missing values (-9999) at some grid points.
我正在处理的数据在某些网格点包含缺失值 (-9999)。 Is there any efficient pythonic way to replace these values with interpolated data using xarray?
是否有任何有效的 pythonic 方法可以使用 xarray 将这些值替换为插值数据?
For example I have something like:例如我有类似的东西:
>>> da = xr.DataArray([[1.0,2.0,3.0],[4.0,-999.0,6.0],[7.0,-999.0,9.0]],[('x',[1,2,3]),('y',[1,2,3])])
>>> da
<xarray.DataArray (x: 3, y: 3)>
array([[ 1., 2., 3.],
[ 4., -9999., 6.],
[ 7., -9999., 9.]])
Coordinates:
* x (x) int64 1 2 3
* y (y) int64 1 2 3
and I want to replace -9999 values with the interpolated values based on adjacent grid points.我想用基于相邻网格点的插值替换 -9999 值。 Any hint would be appreciated!
任何提示将不胜感激!
You can use da.interpolate_na()
to do one dimensional interpolation of NA values - I am unsure if there is a two dimensional method.您可以使用
da.interpolate_na()
对 NA 值进行一维插值 - 我不确定是否有二维方法。
You can convert your -999 values to NaN's and then interpolate.您可以将 -999 值转换为 NaN,然后进行插值。
da = xr.DataArray([[1.0,2.0,3.0],[4.0,-999.0,6.0],[7.0,-999.0,9.0]],[('x',[1,2,3]),('y',[1,2,3])])
da
<xarray.DataArray (x: 3, y: 3)>
array([[ 1., 2., 3.],
[ 4., -999., 6.],
[ 7., -999., 9.]])
Coordinates:
* x (x) int64 1 2 3
* y (y) int64 1 2 3
new_da = da.where(da != -999.0, np.nan)
new_da
<xarray.DataArray (x: 3, y: 3)>
array([[ 1., 2., 3.],
[ 4., nan, 6.],
[ 7., nan, 9.]])
Coordinates:
* x (x) int64 1 2 3
* y (y) int64 1 2 3
new_da.interpolate_na(dim=('y'), method='linear')
<xarray.DataArray (x: 3, y: 3)>
array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
Coordinates:
* x (x) int64 1 2 3
* y (y) int64 1 2 3
Since it's a 1-D interpolation, you can just interpolate for each dimension separately.由于它是一维插值,因此您可以分别为每个维度进行插值。
I still do not think there is an efficient way to do this in xarray.我仍然认为在 xarray 中没有有效的方法来做到这一点。 The suggestion by @bwc will not work properly for multidimensional arrays, because the first pass along the first dimension will already fill all gaps.
@bwc 的建议不适用于多维 arrays,因为第一个维度的第一次通过已经填补了所有空白。 This may be acceptable if your missing values are just single datapoints, but it will result in unwanted behaviour if you have larger gaps.
如果您的缺失值只是单个数据点,这可能是可以接受的,但如果您有更大的差距,它将导致不需要的行为。
The simplest solution I'm aware of for your problem is using the setmisstonn
or setmisstodis
operator in CDO
(depending on how you want to interpolate).对于您的问题,我知道的最简单的解决方案是在
CDO
中使用setmisstonn
或setmisstodis
运算符(取决于您希望如何进行插值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.