简体   繁体   English

读取netcdf4变量属性并将其写入新文件的变量

[英]Read netcdf4 variable attributes and write them to variables of new file

I have a netcdf4 file input.nc4 with variables alpha , beta , gamma . 我有一个netcdf4文件input.nc4,其中包含变量alphabetagamma I want to create a new netcdf4 file output.nc4 with variable names alpha_new , beta_new , gamma_new . 我想创建一个变量名新netcdf4文件output.nc4 alpha_new,beta_new,gamma_new。 The attributes of alpha_new , beta_new and gamma_new should be those of alpha , beta and gamma respectively (in a loop) and the data is simply a numpy array. alpha_newbeta_newgamma_new的属性应该分别是alphabetagamma的属性(循环),并且数据只是一个numpy数组。 I am trying the following but do not know what am I doing wrong or whether it is the right method to do so or not? 我正在尝试以下操作,但不知道我在做什么错,或者这样做是否正确?

import sys
import numpy   as     np
from   netCDF4 import Dataset

input  = Dataset('input.nc4',  'r')
output = Dataset('output.nc4', 'w', format='NETCDF4')

dict1  = {}
for name, variable in input.variables.items():
    dict1[name] = variable

this   = sys.modules[__name__]

for var_name,var_data in dict1.items():
    file.createDimension(var_name,30)
    var_output = output.createVariable('/Group_1/{}'.format(var_name), float, ('{}'.format(var_name),))
    var_nc[:]  = np.linspace(1,30,30)
    setattr(this, '{}_new'.format(var_name) , var_nc[:])

    for attr_name in var_data.ncattrs():
        setattr(this,'vv{}.{}'.format(var_name,attr_name), getattr(var_data,attr_name))

output.close()

where attr_name are units , comments and least_significant_digit and are different for the three variables. 其中attr_name是unitcommentminimum_significant_digit ,并且对于三个变量而言是不同的。 But the above mentioned approach is not working and although the file is created with data, the attributes are not copied and are thus absent. 但是上述方法不起作用,尽管文件是用数据创建的,但属性没有被复制,因此不存在。

To my knowledge, setattr only sets existing netCDF4 attributes, any attributes it creates are attached to the python instance (not inside the dataset / file). 据我所知,setattr仅设置现有的netCDF4属性,它创建的任何属性都将附加到python实例(而不是数据集/文件内部)。 Instead, you need to create a new attribute; 相反,您需要创建一个新属性。 without a method for directly creating attributes, you can use a workaround of creating an arbitrarily named attribute by directly setting it and then renaming it. 如果没有直接创建属性的方法,则可以使用一种解决方法,即直接设置属性,然后重命名,以创建任意命名的属性。

def set_or_create_attr(var, attr_name, attr_value):
    if attr_name in var.ncattrs(): 
        var.setncattr(attr_name, attr_value)
        return
    var.UnusedNameAttribute = attr_value
    var.renameAttribute("UnusedNameAttribute", attr_name)
    return

Using that function in place of setattr should do the trick, the var argument being the dataset or variable the attribute should be attached to. 使用该函数代替setattr应该可以解决问题, var参数是属性应该附加到的数据集或变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM