gpt4 book ai didi

python - 使用 python 更改 netcdf 文件中的维度名称

转载 作者:行者123 更新时间:2023-11-28 21:53:00 31 4
gpt4 key购买 nike

您好,我想编辑 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 - 使用 python 更改 netcdf 文件中的维度名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349196/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com