Python : Replacing Values in netcdf file using netCDF4

孤街浪徒 提交于 2019-12-19 21:27:39

问题


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

回答1:


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

import netCDF4

dset = netCDF4.Dataset('test.nc')

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



回答2:


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() 



回答3:


I know the OP wants a python solution, but in case anyone wants to perform this task only, there is also a quick way to do it from the command line 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



来源:https://stackoverflow.com/questions/31865410/python-replacing-values-in-netcdf-file-using-netcdf4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!