Python NetCDF – How to Change dtype of NetCDF Variable and Rewrite

netcdfnumpypythonxarray

I was wondering how to change the dtype of precipitation from int16 to float64 in the following NetCDF file with these dimensions and variables, and rewrite it as new NetCDF file;

<class 'netCDF4._netCDF4.Dataset'>
root group (NETCDF4 data model, file format HDF5):
    Conventions: CF-1.7
    dimensions(sizes): y(512), n2(2), x(512)
    variables(dimensions): int64 valid_time(), int64 start_time(), float64 y(y), float64 
y_bounds(y,n2), float64 x(x), float64 x_bounds(x,n2), float64 precipitation(y,x), int8 proj()
    groups:

I tried the following codes, but they didn't work;

import xarray as xr
ds=xr.open_dataset('file.nc')
ds.variables['precipitation'].values = ds.variables['precipitation'].values.astype('float64')
ds.to_netcdf('newfile.nc)

In the above script there is no error but the dtype doesn't change.

I also used this script, but it didn't work;

import netCDF4 as nc
ds=nc.Dataset('file.nc')
np.array(ds_time.variables['precipitation'])=ds.createVariable('precipitation','f8',  ('y','x'))

Could please someone (@snowman2) help me with this issue.

Best Answer

I'd use ncap2 from the NetCDF operators (http://nco.sourceforge.net/nco.html#ncap2)

ncap2 -s 'precipitation=double(precipitation)' file.nc newfile.nc

In your example code, you are casting the variable to a float64, but storing it back into a variable already defined as an int16 variable, before copying the dataset out to a new name.

Related Question