我试图绘制多年(1979-2014)的平均温度图,我唯一的问题是尝试从文件夹中读取多个NetCDF(.nc)文件。目前我的程序将绘制单个文件,但我不明白如何使其读取文件夹中的所有文件(每年一个)。我想找到这些年来的平均值。我省略了绘图数据,因为这很好,我需要的唯一帮助是循环遍历单个文件夹中的所有文件
import numpy as np
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import matplotlib.pyplot as plt
q=Dataset('/Users/marjoryrogers/Desktop/July_Temp/MERRA300.prod.assim.tavgM_2d_rad_Nx.201407.SUB-4.nc','r',format='NETCDF4')
q.variables
#jan_temp = q.variables['ts'] # units here, degrees
july_temp = q.variables['ts']
lats = q.variables['latitude']
lons = q.variables['longitude']
#jan_temp.shape
july_temp.shape
lats[:], lons[:]
#q=Dataset('Users/marjoryrogers/Desktop/Spring 2015/Hydroclimatology/MERRA301.prod.assim.tavgM_2d_rad_Nx.200805.SUB.nc', 'r', format='NETCDF4')
july_temp = q.variables['ts']
#jan_july = np.concatenate((may_temp, jun_temp), axis=0)
#jan_july.shape
#aver_temp = np.mean(jan_temp, axis=0)# average temperature
aver_temp2 = np.mean(july_temp, axis=0)
答案 0 :(得分:8)
可以读取多个netcdf文件的netcdf4-python library has a class,使具有记录维度的变量显示为单个大变量。
import netCDF4 as nc
# read multiple files (wildcard)
vn = nc.MFDataset('data_y*.nc')
# read multiple files (file list)
vn = nc.MFDataset(['data_y1997','data_y1998','data_y1999'])
# Variable from multiple files.
airv = vn.variables['ts']