How to remove and identify a key from xarray in order to write a netcdf file?

Viewed 38

I would like to write to a netcdf file my xarray. I have derived it from a netcdf file that I have mask by using a shape file. This how it looks like:

<xarray.Dataset>
Dimensions:              (DATE: 14245, x: 214, y: 173)
Coordinates:
  * DATE                 (DATE) datetime64[ns] 1980-01-01T12:00:00 ... 2018-1...
  * x                    (x) float64 6.168e+05 6.171e+05 ... 6.698e+05 6.701e+05
  * y                    (y) float64 5.113e+06 5.113e+06 ... 5.156e+06 5.156e+06
    transverse_mercator  int64 0
Data variables:
    precipitation        (DATE, y, x) float32 nan nan nan nan ... nan nan nan
Attributes:
    CDI:          Climate Data Interface version 1.9.9 (https://mpimet.mpg.de...
    Conventions:  CF-1.5
    Title:        Daily total precipitation Trentino-South Tyrol 250-meter re...
    Created on:   Fri Feb 26 21:30:51 2021
    history:      Fri Feb 26 23:31:30 2021: cdo -z zip -mergetime DAILYPCP_19...
    CDO:          Climate Data Operators version 1.9.9 (https://mpimet.mpg.de...

If I try to write it as:

ds_subset.to_netcdf('test.nc')

However, I get the following error:

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.

Due to the fact that I am not able to find the key where I have the issue, I have tried to save it as xarray as:

xr.save_mfdataset(ds_subset, 'test.xr')

but I get the following error:

ValueError: cannot use mode='w' when writing multiple datasets to the same path

I would prefer the first solution. I have two thing to point them out: i) I have the felling that the problem is due to the fact that the original file is a dataset; ii) The original netcdf file seems to have some missing field which I fill with rioxarray

However, I am not able to find out where the problem is.

Thanks for nay kind of help.

Here some other, I hope, useful information: this is the result of

ds_subset.precipitation.attrs["grid_mapping"]
Out[3]: 'transverse_mercator'

,

ds_subset.encoding
Out[4]: {}

and

ds_subset.precipitation.encoding
Out[5]: 
{'zlib': True,
 'szip': False,
 'zstd': False,
 'bzip2': False,
 'blosc': False,
 'shuffle': True,
 'complevel': 1,
 'fletcher32': False,
 'contiguous': False,
 'chunksizes': (1, 643, 641),
 'source': 'read file path',
 'original_shape': (14245, 643, 641),
 'dtype': dtype('float32'),
 'missing_value': -999.0,
 '_FillValue': -999.0,
 'grid_mapping': 'transverse_mercator'}
0 Answers
Related