gpt4 book ai didi

python netcdf : making a copy of all variables and attributes but one

转载 作者:太空狗 更新时间:2023-10-29 19:36:50 26 4
gpt4 key购买 nike

我需要处理 netcdf 文件中的单个变量,该文件实际上包含许多属性和变量。我认为更新 netcdf 文件是不可能的(参见问题 How to delete a variable in a Scientific.IO.NetCDF.NetCDFFile? )

我的方法如下:

  1. 从原始文件中获取要处理的变量
  2. 处理变量
  3. 将原始 netcdf 中的所有数据,但处理后的变量复制到最终文件
  4. 将处理后的变量复制到最终文件

我的问题是对步骤 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/

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