I am trying to fill NaNs in a 2-dimensional xarray (lat, lon) with their nearest value.
I have the following example code in which a land-sea-mask is applied. I would then like to fill the ocean points with their respective nearest land point value.
I know bfill and ffill do something along those lines but not exactly what I am looking for.
Ideally, all ocean points should be filled at the end.
Any ideas?
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import regionmask
def mask_ocean(arr, maskValue=np.nan):
land = regionmask.defined_regions.natural_earth.land_110.mask(arr)
masked = xr.where(land==0, arr, maskValue)
return masked
# Create sample data
lon = np.arange(129.4, 153.75+0.05, 0.25)
lat = np.arange(-43.75, -10.1+0.05, 0.25)
data = 10 * np.random.rand(len(lat), len(lon))
ds = xr.Dataset({"DC": (["lat", "lon"], data)}, coords={"lon": lon,"lat": lat})
#< Mask ocean
ds = mask_ocean(ds)
#< Plotting
fig, axes = plt.subplots(nrows=1, ncols=1, subplot_kw={'projection': ccrs.PlateCarree()}) # Use PlateCarree projection
ds['DC'].plot(ax=axes, cmap='Spectral_r', add_colorbar=True, extend='both')
axes.coastlines() # Add coastlines
plt.show()