【问题标题】:python load OpenDap to NetcdfFilepython将OpenDap加载到NetcdfFile
【发布时间】:2017-07-08 19:17:09
【问题描述】:

我正在使用 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

希望有人能帮忙,谢谢!

【问题讨论】:

    标签: python netcdf opendap


    【解决方案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 documentation 有另一个例子说明如何做到这一点。

    【讨论】:

      【解决方案2】:

      这很简单;创建一个新的 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-02-26
        • 2016-02-10
        • 1970-01-01
        • 2014-02-12
        • 2019-07-04
        • 2019-01-04
        • 2020-04-03
        • 2023-03-26
        • 2018-11-26
        相关资源
        最近更新 更多