5

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)

1 Answer 1

13

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.