I am attempting to make a plot of mean temperatures of multiple years (1979-2014), the only problem I am having is attempting to read multiple NetCDF (.nc) files from a folder. At the moment my program will plot a single file, but I do not understand how to make it read all files in a folder (one for each year). I want to find the mean for all of the years. I left out the plot data, because that is fine, the only help I need is in looping through all files in a single folder
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)
The netcdf4-python library has a class that can read multiple netcdf files making variables that has a record dimension appear as a single big variable.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With