[英]Change dimension name in netcdf file with python
嗨,我想编辑 NetCDF 文件中的一些信息,举个例子,假设你有一个文件的 ncdump 和下一个信息:
NetCDF dimension information:
Name: lon
size: 144
type: dtype('float64')
Name: lat
size: 73
type: dtype('float64')
Name: time
size: 29220
type: dtype('float64')
NetCDF variable information:
Name: rlut
dimensions: (u'time', u'lat', u'lon')
type: dtype('float32')
我想将 'lon' 更改为 'longitude'。 我试过:
from netCDF4 import Dataset
path="Here goes the file path"
f=Dataset(path,'r+')
f.renameDimension(u'lon',u'longitude')
f.close()
但是在此之后,当我尝试再次读取文件以执行不同的操作时,该文件不再起作用。
任何帮助我都会谢谢你。
感谢 N1B4 建议使用 NCO,它是工作和编辑 NetCDF 文件的一个非常好的选择。
我想在这里为任何可能对使用 python 和 netcdf4 库修改 NetCDF 文件感兴趣的人发布我的解决方案的草图。 这个想法是创建一个新的 NetCDF 文件,从现有文件导入信息。
#First import the netcdf4 library
from netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/
# Read en existing NetCDF file and create a new one
# f is going to be the existing NetCDF file from where we want to import data
# and g is going to be the new file.
f=Dataset('pathtoexistingfile','r') # r is for read only
g=Dataset('name of the new file','w') # w if for creating a file
# if the file already exists it
# file will be deleted
# To copy the global attributes of the netCDF file
for attname in f.ncattrs():
setattr(g,attname,getattr(f,attname))
# To copy the dimension of the netCDF file
for dimname,dim in f.dimensions.iteritems():
# if you want to make changes in the dimensions of the new file
# you should add your own conditions here before the creation of the dimension.
g.createDimension(dimname,len(dim))
# To copy the variables of the netCDF file
for varname,ncvar in f.variables.iteritems():
# if you want to make changes in the variables of the new file
# you should add your own conditions here before the creation of the variable.
var = g.createVariable(varname,ncvar.dtype,ncvar.dimensions)
#Proceed to copy the variable attributes
for attname in ncvar.ncattrs():
setattr(var,attname,getattr(ncvar,attname))
#Finally copy the variable data to the new created variable
var[:] = ncvar[:]
f.close()
g.close()
我希望这对你有用。
如果你不需要使用 Python,我推荐 NCO 的ncrename
函数: http : ncrename
ncrename -d lon,longitude sample_file.nc
尽管这是一篇很老的帖子,但添加以下内容可能仍然很有价值:
Ajaramillo 指示的方法在我的情况下不起作用,因为它也缺少重命名变量名称,而不仅仅是维度名称。 这对我有用:
from netCDF4 import Dataset
path="Here goes the file path"
f=Dataset(path,'r+')
f.renameDimension(u'lon',u'longitude')
f.renameVariable(u'lon',u'longitude')
f.renameDimension(u'lat',u'latitude')
f.renameVariable(u'lat',u'latitude')
f.close()
我认为您还需要修改对重命名维度的任何引用。 例如,您的变量 rlut,其维度为“lon”,已重命名为“longitude”。 不确定这是否可以通过就地编辑来完成。 您可能需要使用以下方法创建文件的新副本:
createVariable('rlut', 'f4', ('time', 'lat', 'longitude')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.