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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With