我有一个一维数组,它是一个按时间序列的每小时数据集,包含49090个点,需要转换为netcdf格式。
在下面的代码中,result_u2是一个1d数组,用于存储for循环的结果。它具有49090个数据点。
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()
我是编程新手。我在上面尝试的代码应该能够写入nc文件,但是在运行脚本时未创建任何nc文件。请帮助。
引用netCDF4
documentation,您的代码可能看起来像
import datetime
import netCDF4
import numpy as np
# using "with" syntax so cleanup is done automatically
with netCDF4.Dataset('D:/output.nc', 'w', 'NETCDF3') 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 a dummy here...
wind[:] = np.random.rand(nhours)
我的建议是,如果要使用netCDF4
包,则应大致了解Python语法。例如。 Python代码中没有分号。然后,查看docs-您在此处找到的教程基本上涵盖了您在此处要问的内容。