Python读取NetCDF4文件触发NameError:lat_array未定义
Fixing NameError: 'lat_array'/'lon_array' is not defined in NetCDF4 Python Script
Looks like you hit a simple variable name typo here—your script throws a NameError because you’re referencing lat_array and lon_array, but those variables were never defined. Looking at your code’s logic, you clearly intended to use the target coordinates you already set up: lat_target and lon_target.
Fixed Full Code
#!/usr/bin/python #========================================================= from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt #========================================================= # SET TARGET DATA #========================================================= day=1 lat_target=45.0 lon_target=360-117.0 #========================================================= # SET OPENDAP PATH #========================================================= pathname = 'http://thredds.northwestknowledge.net:8080/thredds/dodsC/agg_macav2metdata_huss_BNU-ESM_r1i1p1_historical_1950_2005_CONUS_daily.nc' #========================================================= # GET DATA HANDLES #========================================================= filehandle=Dataset(pathname,'r',format="NETCDF4") lathandle=filehandle.variables['lat'] lonhandle=filehandle.variables['lon'] timehandle=filehandle.variables['time'] datahandle=filehandle.variables['specific_humidity'] #========================================================= # GET DATA #========================================================= #get data time_num=len(timehandle) timeindex=range(day-1,time_num,365) #python starts arrays at 0 time=timehandle[timeindex] lat = lathandle[:] lon = lonhandle[:] #========================================================= #find indices of target lat/lon/day # Fix: Replace lat_array with lat_target, lon_array with lon_target lat_index = (np.abs(lat - lat_target)).argmin() lon_index = (np.abs(lon - lon_target)).argmin() #check final is in right bounds if(lat[lat_index]>lat_target): if(lat_index!=0): lat_index = lat_index - 1 if(lat[lat_index]<lat_target): if(lat_index!=len(lat)-1): # Fix: Avoid index out of bounds (max index is len(lat)-1) lat_index =lat_index +1 if(lon[lon_index]>lon_target): if(lon_index!=0): lon_index = lon_index - 1 if(lon[lon_index]<lon_target): if(lon_index!=len(lon)-1): # Same fix for longitude index lon_index = lon_index + 1 # Rename variables to avoid overwriting the original arrays lat_selected = lat[lat_index] lon_selected = lon[lon_index] #========================================================= #get data data = datahandle[timeindex,lat_index,lon_index] #========================================================= # MAKE A PLOT #========================================================= yearref=1950 years = np.arange(yearref,yearref+len(time)) fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel(u'Year') ax.set_ylabel(u'Specific Humidity') ax.set_title(u'Specific Humidity on Day %d ,\n %4.2f°N, %4.2f°W' % (day, lat_selected, abs(360 - lon_selected))) #ax.plot_date(x=time,y=data,fmt="b-") ax.ticklabel_format(style='plain') ax.plot(years,data,'b-') plt.savefig("myPythonGraph.png") plt.show()
Key Fixes & Improvements
- Fix the Typo (Root Cause):The
NameErrorhappens because you wrotelat_array/lon_arrayinstead oflat_target/lon_target. The line(np.abs(lat - lat_target)).argmin()calculates the absolute difference between every latitude in the NetCDF file and your target, then finds the index of the closest match—exactly what you need to pull data for your desired location. - Prevent Index Out of Bounds:Your original code had
if(lat_index!=len(lat))which would cause an error iflat_indexreached the last position (since array indices go from0tolen(lat)-1). Changing this tolen(lat)-1keeps things safe. - Avoid Variable Overwriting:You originally overwrote the
latandlonarrays with single values, which could cause confusion if you wanted to reuse the full coordinate arrays later. Renaming the selected coordinates tolat_selected/lon_selectedkeeps things clear.
内容的提问来源于stack exchange,提问作者Markus Haas
相关产品推荐
相关产品推荐

