Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple NetCDF files from a folder in python

Tags:

python

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)
like image 815
Colton Rogers Avatar asked Jan 09 '23 15:01

Colton Rogers


1 Answers

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']
like image 166
Favo Avatar answered Jan 17 '23 15:01

Favo