简体   繁体   English

在Python中从NetCDF文件中读取4d var

[英]Reading 4d var from NetCDF file in Python

I am using Scientific.IO.NetCDF to read NetCDF data into Python. 我正在使用Scientific.IO.NetCDF将NetCDF数据读入Python。 I am trying to read a 4d 32bit variable with size (366,30,476,460) but I end up with zeros in my ndarray. 我试图读取一个4d 32位变量的大小(366,30,476,460),但我最终在我的ndarray中使用了零。 Strangely if I read just the 3d data (1,30,476,460), the returned values are ok. 奇怪的是,如果我只读取3d数据(1,30,476,460),返回的值就可以了。

This is what I am trying to do: 这就是我想要做的:

from Scientific.IO.NetCDF import NetCDFFile as Dataset
from collections import namedtuple

# Define output data structure as a named tuple
Roms_data=namedtuple('Roms_data','Ti Tf Nt U V W Zeta')

# Open the NetCDF file for reading.
ncfile = Dataset(data_file,'r')

if Tstart==-1:
  ti=0
  tf=NTsav-1
else:
  ti=Tstart-1
  tf=Tend-1

try:
  udata = ncfile.variables['u'][:]
  print str(udata.shape)
except:
  print ' Failed to read u data from '+data_file

The "[:]" means i am reading the whole 4d variable 'u' into an ndarray called udata. “[:]”表示我正在将整个4d变量“u”读入名为udata的ndarray中。 This does not work and udata is full of zeros. 这不起作用,udata充满了零。 However, if I do: 但是,如果我这样做:

try:
  udata = ncfile.variables['u'][0,:,:,:]
  print str(udata.shape)
except:
  print ' Failed to read u data from '+data_file

then "udata" that is now a 3d ndarray has the values it is supposed to read from the NetCDF file. 那么现在是3d ndarray的“udata”具有它应该从NetCDF文件中读取的值。

Any help? 有帮助吗? Thanks in advance. 提前致谢。

It is unclear to me what may cause your problem, but I have one alternative suggestionyou may try. 我不清楚什么可能导致你的问题,但我有一个替代建议你可能会尝试。 It seems you are reading NetCDF4 data output from a ROMS ocean model. 您似乎正在从ROMS海洋模型中读取NetCDF4数据输出。 I do this regularily, but I always prefer to use the netcdf-python module for this: 我经常这样做,但我总是喜欢使用netcdf-python模块

 from netCDF4 import Dataset
 cdf=Dataset("ns8km_avg_16482_GLORYS2V1.nc","r")
 u=cdf.variables["u"][:]

One benefit of the netcdf-python module is that it automatically adjusts for offset, scale, and fill_value in a netcdf file. netcdf-python模块的一个好处是它可以自动调整netcdf文件中的offset,scale和fill_value The 4D array read from the netcdf file will therefore contain masked values. 因此,从netcdf文件读取的4D数组将包含屏蔽值。 I wonder if the masking in your approach is not done correctly. 我想知道你的方法中的掩蔽是否没有正确完成。 Perhaps you could try installing netcdf-python and read your data with this approach and hopefully it could help. 也许您可以尝试安装netcdf-python并使用这种方法读取您的数据,并希望它可以提供帮助。 Cheers, Trond 干杯,特隆德

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

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