作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我需要处理 netcdf 文件中的单个变量,该文件实际上包含许多属性和变量。我认为更新 netcdf 文件是不可能的(参见问题 How to delete a variable in a Scientific.IO.NetCDF.NetCDFFile? )
我的方法如下:
我的问题是对步骤 3 进行编码。我从以下内容开始:
def processing(infile, variable, outfile):
data = fileH.variables[variable][:]
# do processing on data...
# and now save the result
fileH = NetCDFFile(infile, mode="r")
outfile = NetCDFFile(outfile, mode='w')
# build a list of variables without the processed variable
listOfVariables = list( itertools.ifilter( lamdba x:x!=variable , fileH.variables.keys() ) )
for ivar in listOfVariables:
# here I need to write each variable and each attribute
如何在无需重建整个数据结构的情况下将所有数据和属性保存在少量代码中?
最佳答案
这是我刚刚使用和工作的。 @arne 的答案针对 Python 3 进行了更新,还包括复制变量属性:
import netCDF4 as nc
toexclude = ['ExcludeVar1', 'ExcludeVar2']
with netCDF4.Dataset("in.nc") as src, netCDF4.Dataset("out.nc", "w") as dst:
# copy global attributes all at once via dictionary
dst.setncatts(src.__dict__)
# copy dimensions
for name, dimension in src.dimensions.items():
dst.createDimension(
name, (len(dimension) if not dimension.isunlimited() else None))
# copy all file data except for the excluded
for name, variable in src.variables.items():
if name not in toexclude:
x = dst.createVariable(name, variable.datatype, variable.dimensions)
dst[name][:] = src[name][:]
# copy variable attributes all at once via dictionary
dst[name].setncatts(src[name].__dict__)
关于 python netcdf : making a copy of all variables and attributes but one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15141563/
我是一名优秀的程序员,十分优秀!