Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 681
user308827 Avatar asked Aug 06 '15 20:08

user308827


3 Answers

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
like image 65
jhamman Avatar answered Oct 09 '22 23:10

jhamman


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() 
like image 41
Adrien Bax Avatar answered Oct 10 '22 01:10

Adrien Bax


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

like image 26
Adrian Tompkins Avatar answered Oct 09 '22 23:10

Adrian Tompkins