Search code examples
pythonnetcdf

converting a 1d array to netcdf


I have a 1d array which is a time series hourly dataset encompassing 49090 points which needs to be converted to netcdf format.

In the code below, result_u2 is a 1d array which stores result from a for loop. It has 49090 datapoints.

nhours = 49091;#one added to no of datapoints
unout.units = 'hours since 2012-10-20 00:00:00'
unout.calendar = 'gregorian'
ncout = Dataset('output.nc','w','NETCDF3');  
ncout.createDimension('time',nhours); 
datesout = [datetime.datetime(2012,10,20,0,0,0)+n*timedelta(hours=1) for n in range(nhours)]; # create datevalues
timevar = ncout.createVariable('time','float64',('time'));timevar.setncattr('units',unout);timevar[:]=date2num(datesout,unout);
winds = ncout.createVariable('winds','float32',('time',));winds.setncattr('units','m/s');winds[:] = result_u2;
ncout.close()

I'm new to programming. The code I tried above should be able to write the nc file but while running the script no nc file is being created. Please help.


Solution

  • My suggestions would be to have a look at Python syntax in general, if you want to use it / the netCDF4 package. E.g. there are no semicolons in Python code.

    Check out the API documentation - the tutorial you find there basically covers what you're asking. Then, your code could look like

    import datetime
    import netCDF4
    
    # using "with" syntax so you don't have to do the cleanup:
    with netCDF4.Dataset('output.nc', 'w', format='NETCDF3_CLASSIC') as ncout:
        # create time dimension
        nhours = 49091
        time = ncout.createDimension('time', nhours)
    
        # create the time variable
        times = ncout.createVariable('time', 'f8', ('time',))
        times.units = 'hours since 2012-10-20 00:00:00'
        times.calendar = 'gregorian'
    
        # fill time
        dates = [datetime.datetime(2012,10,20,0,0,0)+n*datetime.timedelta(hours=1) for n in range(nhours)]
        times[:] = netCDF4.date2num(dates, units=times.units, calendar=times.calendar)
    
        # create variable 'wind', dependent on time
        wind = ncout.createVariable('wind', 'f8', ('time',))
        wind.units = 'm/s'
        # fill with data, using your 1d array here:
        wind[:] = result_u2