本文介绍了python netcdf:复制所有变量和属性,但复制一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理netcdf文件中的单个变量,该文件实际上包含许多属性和变量.我认为无法更新netcdf文件(请参阅问题如何删除Scientific.IO.NetCDF.NetCDFFile中的变量?)

I need to process a single variable in a netcdf file that actually contains many attributes and variable.I think it is not possible to update a netcdf file (see question How to delete a variable in a Scientific.IO.NetCDF.NetCDFFile?)

我的方法如下:

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

我的问题是对步骤3进行编码.我从以下内容开始:

My problem is to code step 3. I started with the following:

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

如何在不重建整个数据结构的情况下将全部数据和属性保存在完整的代码中?

How can I save all data and attribute in a handfull of code without having to rebuild a whole structure of data?

推荐答案

这就是我刚刚使用和工作的内容. @arne的答案已针对Python 3更新,并包括复制变量属性:

Here's what I just used and worked. @arne's answer updated for Python 3 and also to include copying variable attributes:

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:复制所有变量和属性,但复制一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:36