I am trying to save clipped NetCDF by shapefile. I've tried use any relevant parameter or drop crs variable (drop_vars), however without success.
Here is my snippet:
import rioxarray as rxr
import rasterio as rio
import xarray as xr    
xds = xr.open_dataset(file.nc)
geodf = gpd.read_file(shape.shp)
xds.rio.write_crs("EPSG:4326", inplace=True)
clipped = xds.rio.clip(geodf.geometry.apply(mapping), geodf.crs)
clipped.to_netcdf("test.nc")
out:
ValueError: failed to prevent overwriting existing key grid_mapping in attrs. This is 
probably an encoding field used by xarray to describe how a variable is serialized. To 
proceed, remove this key from the variable's attributes manually.
However rioxarray function saving the dataset to GeoTiff is working well.
clipped.rio.to_raster("file.tif", driver="GTiff")
Many thanks for any suggestion on how to proceed.
PS: There is no time dimension only Lat/Lon and Variables - NDVI
I had the same problem. I solved it by dropping the grid_mapping attribute that is created when you write the CRS.
This worked for me. Let's see xr_df is my xarray dataset:
vars_list = list(xr_df.data_vars)  
    for var in vars_list:  
        del xr_df[var].attrs['grid_mapping']
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With