Python : Replacing Values in netcdf file using netCDF4

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

For me, the previous answer does not work, I solved it with:

dset = netCDF4.Dataset('test.nc','r+')
dset.variables['var'][:]
... your changes ...
dset.close() 

Soln 1: Python xarray

This solution uses xarray to read and write the netcdf file, and the package's function where to conditionally reset the values.

import xarray as xr
ds=xr.open_dataset('test.nc')
ds['var']=xr.where((ds['var']<0),-1,ds['var'])
ds.to_netcdf('modified_test.nc') # rewrite to netcdf

Soln 2: NCO from the command line

I know the OP wants a python solution, but in case anyone wants to perform this task only quickly from the command line, there is also a way to do it with nco:

ncap2 -s 'where(x<0.) x=-1;' input.nc -O output.nc

as per this post: setting values below a threshold to the threshold in a netcdf file