Notes on working with NetCDF
ChangeLog --2018/07/04 Added how to specify missing values --2015/09/04 Reflection of comment contents, addition of writing method
NetCDF can be read by the netCDF4 module. Download and install from Github Page, or It comes standard with Anaconda for Mac and Python (x, y) for Windows.
import netCDF4
nc = netCDF4.Dataset('filename.nc', 'r')
dim = len(nc.dimensions['dimname'])
var = nc.variables['varname'][:]
nc.close()
import netCDF4
from numpy import dtype
#Create an object and set each dimension number.
nc = netCDF4.Dataset('filename.nc', 'w', format='NETCDF3_CLASSIC')
nc.createDimension('ntime', len(time_out)) # e.g. time_out = [0, 1, ...]
# nc.createDimensions('ntime', None) #When setting to unlimited
nc.createDimension('xi', x) # e.g. x = 10
nc.createDimension('eta', y) # e.g. y = 10
#After that, define each variable.
#The following example defines time, latitude, longitude, and 3D variables.
time = nc.createVariable('time', dtype('int32').char, ('ntime',))
time.long_name = 'time of test variable'
time.units = 'days since 1968-05-23 00:00:00'
lon = nc.createVariable('lon', dtype('double').char, ('eta', 'xi'))
lon.long_name = 'east longitude'
lon.units = 'degree of east longitude'
lat = nc.createVariable('lat', dtype('double').char, ('eta', 'xi'))
lat.long_name = 'north latitude'
lat.units = 'degree of north latitude'
var = nc.createVariable('varname', dtype('double').char, ('ntime', 'eta', 'xi'))
var.long_name = 'test variable'
var.units = 'unit of test variable'
#Finally, np in advance.Substitute the value created by ndarray etc.
time[:] = time_out
lon[:,:] = lon_out
lat[:,:] = lat_out
var[:,:,:] = var_out
nc.close()
If you want to treat a specific value as a missing value, you can set fill_value
when creating the variable.
# -When 999 is a missing value
var = nc.createVariable('varname', dtype('double').char, ('ntime', 'eta', 'xi'), fill_value=-999)
(Added on 2018/07/04, Thanks @yutabvb)
Recommended Posts