nc.variables[i].units
显示错误attribute not found
。我试图从netcdf文件中提取数据。如何提取特定经度或纬度的数据?
from netCDF4 import Dataset
nc=Dataset("test.nc",'r')
for i in nc.variables:
print(i,nc.variables[i].units,nc.variables[i].shape)
lat=nc.variables['lat'][:]
print(lat)
输出如下:
area meter2 (128, 256)
lat degrees_north (128,)
Traceback (most recent call last):
File "C:\Users\harsh\Desktop\cv\test_netcdf.py", line 7, in <module>
print(i,nc.variables[i].units,nc.variables[i].shape) #nc.variable[i].units
File "netCDF4\_netCDF4.pyx", line 4303, in
netCDF4._netCDF4.Variable.__getattr__
File "netCDF4\_netCDF4.pyx", line 4114, in
netCDF4._netCDF4.Variable.getncattr
File "netCDF4\_netCDF4.pyx", line 1392, in netCDF4._netCDF4._get_att
File "netCDF4\_netCDF4.pyx", line 1857, in
netCDF4._netCDF4._ensure_nc_success
AttributeError: NetCDF: Attribute not found
答案 0 :(得分:1)
仔细阅读本节
for i in nc.variables:
print(i,nc.variables[i].units,nc.variables[i].shape)
在此for循环中,我不是整数。由于对每个循环将其评估为a,因此它代表当前变量,而不是该变量所在的索引。您在这里有几个选择
选择一:改为使用范围
for i in range(len(nc.variables)):
print(i,nc.variables[i].units,nc.variables[i].shape)
选项二:使用zip引用变量和整数
正如Bart所指出的那样,枚举是一种更好的方法。看到他对此的评论
for i, variable in zip(range(len(nc.variables)), nc.variables):
print(i, variable.units, variable.shape)
选择三:避免完全使用我
for variable in nc.variables:
print(variable.units, variable.shape)