2

我正在使用 URL 从 opendap 服务器(数据的子集)打开 netcdf 数据。当我打开它时,数据(据我所见)在请求变量之前并未实际加载。我想将数据保存到磁盘上的文件中,我该怎么做?

我目前有:

import numpy as np
import netCDF4 as NC

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here

# now i want to save this data to a file (for example test.nc), set.close() obviously wont work

希望有人能帮忙,谢谢!

4

2 回答 2

1

这很简单;创建一个新的 NetCDF 文件,然后复制您想要的任何内容 :) 幸运的是,这可以在很大程度上自动化,从输入文件复制正确的尺寸、NetCDF 属性……。我快速编写了这个例子,输入文件也是一个本地文件,但是如果用 OPenDAP 读取已经可以工作,它应该以类似的方式工作。

import netCDF4 as nc4

# Open input file in read (r), and output file in write (w) mode:
nc_in = nc4.Dataset('drycblles.default.0000000.nc', 'r')
nc_out = nc4.Dataset('local_copy.nc', 'w')

# For simplicity; copy all dimensions (with correct size) to output file
for dim in nc_in.dimensions:
    nc_out.createDimension(dim, nc_in.dimensions[dim].size)

# List of variables to copy (they have to be in nc_in...):
# If you want all vaiables, this could be replaced with nc_in.variables
vars_out = ['z', 'zh', 't', 'th', 'thgrad']

for var in vars_out:
    # Create variable in new file:
    var_in  = nc_in.variables[var]
    var_out = nc_out.createVariable(var, datatype=var_in.dtype, dimensions=var_in.dimensions)

    # Copy NetCDF attributes:
    for attr in var_in.ncattrs():
        var_out.setncattr(attr, var_in.getncattr(attr))

    # Copy data:
    var_out[:] = var_in[:]

nc_out.close()

希望它有帮助,如果不让我知道。

于 2017-07-06T14:57:27.643 回答
1

如果你可以使用 xarray,这应该是:

import xarray as xr

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
ds = xr.open_dataset(url, engine='netcdf4')  # or engine='pydap'
ds.to_netcdf('test.nc')

xarray文档有另一个示例说明如何执行此操作。

于 2017-07-06T17:07:58.740 回答