您好我想编辑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'。我尝试过:
from netCDF4 import Dataset
path="Here goes the file path"
f=Dataset(path,'r+')
f.renameDimension(u'lon',u'longitude')
f.close()
但在此之后,当我尝试再次读取文件以执行不同的操作时,该文件不再起作用。
任何帮助我都会感谢你。
答案 0 :(得分:3)
感谢N1B4建议使用NCO,这是一个非常好的工作和编辑NetCDF文件的选项。
我想在这里发布我的解决方案草图,可能有兴趣使用netcdf4库使用python修改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 exists it the
# file will be deleted to write on it
# 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()
我希望这对你有用。
答案 1 :(得分:2)
即使这是一个很老的帖子,添加它仍然可能很有价值:
在我的案例中,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()
答案 2 :(得分:1)
如果您不需要使用Python,我建议使用NCO ncrename
函数:http://nco.sourceforge.net/nco.html#ncrename-netCDF-Renamer
ncrename -d lon,longitude sample_file.nc
答案 3 :(得分:1)
我认为您还需要修改对重命名维度的任何引用。例如。你的变量rlut,它的维度是' lon',它已被重命名为经度'。不确定是否可以通过就地编辑来完成。您可能需要使用以下方法创建文件的新副本:
createVariable('rlut', 'f4', ('time', 'lat', 'longitude')