在Python中从NetCDF文件读取4D变量

3
我正在使用Scientific.IO.NetCDF将NetCDF数据读入Python。我试图读取一个大小为(366,30,476,460)的4d 32位变量,但是我的ndarray中最终得到的只有零值。奇怪的是,如果我只读取3d数据(1,30,476,460),返回的值就是正确的。
这是我想要做的事情:
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

“[:]”的意思是我正在将整个4D变量“u”读取到一个称为“udata”的ndarray中。但这样做不起作用,udata中全是零。然而,如果我这样做:
try:
  udata = ncfile.variables['u'][0,:,:,:]
  print str(udata.shape)
except:
  print ' Failed to read u data from '+data_file

那么现在的“udata”是一个3D的ndarray,具有从NetCDF文件中读取的值。

需要帮忙吗?提前感谢。


如果可能的话,建议将您的netCDF文件放在Dropbox(或某个等效服务)上,以便我们可以进行实验。 - Julien Chastang
1个回答

1

我不确定什么原因导致了你的问题,但是我有一个备选建议可以尝试。看起来你正在从ROMS海洋模型读取NetCDF4数据输出。我经常这样做,但我总是更喜欢使用 netcdf-python模块

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

netcdf-python模块的一个好处是它能够自动调整netcdf文件中的offset,scale和fill_value。从netcdf文件读取的4D数组将包含掩码值。我想知道你的方法中遮罩是否正确。也许你可以尝试安装netcdf-python并使用这种方法读取数据,希望它能有所帮助。 问候,Trond


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接