pythonnetcdfpython-xarraynco

Python : Replacing Values in netcdf file using netCDF4


I have a netcdf file with several values < 0. I would like to replace all of them with a single value (say -1). How do I do that using netCDF4? I am reading in the file like this:

import netCDF4

dset      = netCDF4.Dataset('test.nc')
dset[dset.variables['var'] < 0] = -1

Solution

  • If you want to keep the data in the netCDF variable object, this should work:

    import netCDF4
    
    dset = netCDF4.Dataset('test.nc', 'r+')
    
    dset['var'][:][dset['var'][:] < 0] = -1
    
    dset.close() # if you want to write the variable back to disk
    

    If you don't want to write back to disk, go ahead and just get the numpy array and slice/assign to it:

    data = dset['sea_ice_cover'][:]  # data is a numpy array
    data[data < 0] = -1