社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

用Python的netCDF4模块写nc文件

happy科研 • 3 年前 • 374 次点击  

现在处理nc文件,尤其是业务化的时候,用xarray模块的比较多,因为速度更快,而且也更稳定。但是netCDF4模块也很常用,事实上我们有很多既有代码就是基于netCDF4写的。这里存一下netCDF4模式写nc文件的代码:

# -*- coding: utf-8 -*-import numpy as npimport sysimport osfrom netCDF4 import Datasetimport timefrom datetime import datetime, timedeltafrom netCDF4 import num2date, date2num
def creatspinc(value, filename):    gridspi = Dataset(filename, 'w', format='NETCDF4')
   # dimensions    gridspi.createDimension('time'None)    gridspi.createDimension('lat'1000)   #len(lat) gridspi.createDimension('lon', 2000)   # Create coordinate variables for dimensions    times = gridspi.createVariable('time', np.float64, ('time',))    latitudes = gridspi.createVariable('lat', np.float32, ('lat',)) longitudes = gridspi.createVariable('lon', np.float32, ('lon',))
    # Create the actual variable var = gridspi.createVariable('var', np.float32, ('time', 'lat', 'lon',))      # Global Attributes      gridspi.description = 'var'    gridspi.history = 'Created ' + time.ctime(time.time())    gridspi.source = 'netCDF4 python module tutorial'       # Variable Attributes    latitudes.units = 'degree_north'    longitudes.units = 'degree_east'    times.units = 'days since 2019-01-01 00:00:00' times.calendar = 'gregorian'    # data    lats = np.linspace(25.,35.,1000#notice: the last numb is not included lons = np.linspace(95.,115.,2000) #notice: the last numb is not included
    latitudes[:] = lats    longitudes[:] = lons        #--Fill in values      var[0:value.shape[0],:,:] = value        # Fill in times dates = []
    for n in range(var.shape[0]): dates.append(datetime(2019, 1, 1) + n * timedelta(days=1))
    times[:] = date2num(dates, units = times.units,calendar = times.calendar) print 'time values (in units %s): ' % times.units +'\n', times[:]
dates = num2date(times[:], units=times.units, calendar=times.calendar)
    gridspi.close()
return
if __name__ == '__main__': out_dir='~/' out_file_nc = out_dir+'out.nc' data_nc = np.zeros(shape=(61,1000,2000))     creatspinc(data_nc, out_file_nc)




Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/119914
 
374 次点击