In [1]:
import netCDF4

In [9]:
f = netCDF4.MFDataset('/usgs/data2/rsignell/models/ncep/narr/air.2m.19??.nc')

In [10]:
f.variables.keys()


Out[10]:
[u'lat',
 u'lon',
 u'x',
 u'y',
 u'Lambert_Conformal',
 u'time',
 u'time_bnds',
 u'air']

In [49]:
shape(f.variables['x'])


Out[49]:
(349,)

In [51]:
atemp = f.variables['air']
print atemp
print f.variables['Lambert_Conformal']


<class 'netCDF4._Variable'>
int16 air('time', 'y', 'x')
    units: K
    long_name: Daily Air Temperature at 2 m
    unpacked_valid_range: [ 151.  400.]
    precision: 0.00379979
    actual_range: [ 219.79893494  312.32373047]
    missing_value: 32767
    valid_range: [-32765  32765]
    _FillValue: -32767
    GRIB_name: TMP
    GRIB_id: 11
    var_desc: Air temperature
    standard_name: air_temperature
    level_desc: 2 m
    dataset: NARR Daily Averages
    statistic: Mean
    parent_stat: Individual Obs
    grid_mapping: Lambert_Conformal
    coordinates: lat lon
    add_offset: 275.5
    scale_factor: 0.00379979
    cell_methods: time: mean (of 8 3-hourly values in one day)
unlimited dimensions = ('time',)
current size = (731, 277, 349)

<type 'netCDF4.Variable'>
int32 Lambert_Conformal()
    grid_mapping_name: lambert_conformal_conic
    standard_parallel: [ 50.  50.]
    longitude_of_central_meridian: -107.0
    latitude_of_projection_origin: 50.0
    false_easting: 5632642.22547
    false_northing: 4612545.65137
unlimited dimensions = ()
current size = ()


In [12]:
ntimes, ny, nx = shape(atemp)

In [36]:
cold_days = zeros((ny,nx),dtype=int)
for i in xrange(ntimes):
    cold_days += atemp[i,:,:].data-273.15 < 0

In [44]:
pcolormesh(cold_days)
colorbar()


Out[44]:
<matplotlib.colorbar.Colorbar instance at 0x17236560>

In [67]:
# create NetCDF file
nco = netCDF4.Dataset('/usgs/data2/notebook/cold_days.nc','w',clobber=True)
nco.createDimension('x',nx)
nco.createDimension('y',ny)

cold_days_v = nco.createVariable('cold_days', 'i4',  ( 'y', 'x'))
cold_days_v.units='days'
cold_days_v.long_name='total number of days below 0 degC'
cold_days_v.grid_mapping = 'Lambert_Conformal'

In [68]:
lono = nco.createVariable('lon','f4',('y','x'))
lato = nco.createVariable('lat','f4',('y','x'))
xo = nco.createVariable('x','f4',('x'))
yo = nco.createVariable('y','f4',('y'))
lco = nco.createVariable('Lambert_Conformal','i4')

In [69]:
# copy all the variable attributes from original file
for var in ['lon','lat','x','y','Lambert_Conformal']:
    for att in f.variables[var].ncattrs():
        setattr(nco.variables[var],att,getattr(f.variables[var],att))

In [70]:
# copy variable data for lon,lat,x and y
lono[:]=f.variables['lon'][:]
lato[:]=f.variables['lat'][:]
xo[:]=f.variables['x'][:]
yo[:]=f.variables['y'][:]

#  write the cold_days data
cold_days_v[:,:]=cold_days

# copy Global attributes from original file
for att in f.ncattrs():
    setattr(nco,att,getattr(f,att))

nco.Conventions='CF-1.6'
nco.close()

In [ ]: