使用python在netcdf文件中定义单位

使用python在netcdf文件中定义单位,python,unit-testing,netcdf,units-of-measurement,Python,Unit Testing,Netcdf,Units Of Measurement,我正在创建一个带有几个变量的netcdf文件。我得到的netcdf文件和我预期的一样有用,但我不知道如何定义变量的单位 这就是我的代码现在的样子: import netCDF4 import numpy as np ncfile = netCDF4.Dataset('state.global.nc', 'r') u = ncfile.variables['U'][:,:,:,:] # [T,Z,Y,X] v = ncfile.variables['V'][:,:,:,:] nx = np.sh

我正在创建一个带有几个变量的netcdf文件。我得到的netcdf文件和我预期的一样有用,但我不知道如何定义变量的单位

这就是我的代码现在的样子:

import netCDF4
import numpy as np

ncfile = netCDF4.Dataset('state.global.nc', 'r')
u = ncfile.variables['U'][:,:,:,:] # [T,Z,Y,X]
v = ncfile.variables['V'][:,:,:,:]
nx = np.shape(u)[3] - 1
ny = np.shape(v)[2] - 1
nz = np.shape(u)[1]

u_c = 0.5 * (u[:,:,:,0:nx] + u[:,:,:,1:nx+1])
v_c = 0.5 * (v[:,:,0:ny,:] + v[:,:,1:ny+1,:])

u_center = np.fliplr(u_c) # Flip upside down
v_center = np.fliplr(v_c)

# Write out u_center and v_center into a new netCDF file
ncfile_out = netCDF4.Dataset('./output.nc', 'w')
ncfile_out.createDimension('X', nx)
ncfile_out.createDimension('Y', ny)
ncfile_out.createDimension('Z', nz)

ncfile_out.createDimension('time', None)
u_out = ncfile_out.createVariable('u_center', 'f4', ('time', 'Z', 'Y', 'X'))
v_out = ncfile_out.createVariable('v_center', 'f4', ('time', 'Z', 'Y', 'X'))
time = ncfile_out.createVariable('Time', 'i4', 'time')

v_out.units = 'm/s' # Define units of variables
u_out.units = 'm/s'
time.units = 's'

u_out[:,:,:,:] = u_center[:,:,:,:]
v_out[:,:,:,:] = v_center[:,:,:,:]
ncfile_out.close()

但是我使用ncview阅读了最终文件,没有看到任何单位,我想将尺寸(x,y,z)单位也定义为“米”。我该怎么做?如果我想把“X”中的1步放在“500米”中呢

定义单位的方法是使用netCDF文件中的属性

尽管您可以按自己喜欢的方式执行此操作,但最好的方法是坚持netCDF约定,为变量定义一个名为“units”的文本属性,并将SI单位放入其中

这里有一个很好的例子:

单位由如下代码定义:

w_nc_var.setncatts({'long_name': u"mean Daily Air temperature",\
                'units': u"degK", 'level_desc': u'Surface',\
                'var_desc': u"Air temperature",\
                'statistic': u'Mean\nM'})
(上面的代码还定义了其他属性,但您可以看到它将“units”设置为“degK”。)

如果需要单位之间的转换,udunits包可以提供帮助。这也是一个很好的地方,让缩写使用你的单位

Udunits也来自Unidata,即维护netCDF的人员