netcdfnetcdf4nco

Change netcdf4 data type


I have a netCDF4 datafile where the time variable is stored as a float (netCDF: 'f8', numpy: float64) and I need to change it to a 32bit int (netCDF: 'i4', numpy: int32). I have tried making the change in python

tds.variables['time'][:] = np.int32(tds.variables['time'][:])

but this hasn't worked. What is the best way to make this change?


Solution

  • Since you tagged the question with nco, I assume a solution with nco is also acceptable.. This can be done with ncap2 (example with a NetCDF file that I had lying around):

    ncdump -h drycblles.default.0000000.nc`:
    

    gives:

    netcdf drycblles.default.0000000 {
    dimensions: 
        z = 128 ;
        zh = 129 ;
        t = UNLIMITED ; // (37 currently)
    variables:  
        double t(t) ;
            t:units = "s" ;
            t:long_name = "Time" ;
    .....
    

    Same dump (of modified file) after:

    ncap2 -s 't=int(t)' drycblles.default.0000000.nc drycblles.default.0000000_2.nc
    

    gives:

    int t(t) ;
        t:long_name = "Time" ;
        t:units = "s" ;
    

    What you are trying in Python won't work since you cast the data of the variable time to int, but still store it as a float (you don't change the variable type in the NetCDF file). I don't see any options to change the data type in place, I guess you could copy the variable time to another name, create a new variable time with type int, copy the data, and remove the old time variable.

    For a 2024 solution with xarray:

    import xarray as xr
    ds = xr.open_dataset('your.nc')
    ds['time'] = ds['time'].astype('int')
    ds.to_netcdf('your_new.nc')