Python實現(xiàn)將數(shù)據(jù)寫入netCDF4中的方法示例
本文實例講述了Python實現(xiàn)將數(shù)據(jù)寫入netCDF4中的方法。分享給大家供大家參考,具體如下:
nc文件為處理氣象數(shù)據(jù)文件。用戶可以去https://www.lfd.uci.edu/~gohlke/pythonlibs/ 搜索netCDF4,下載相應平臺的whl文件,使用pip安裝即可。
這里演示的寫入數(shù)據(jù)操作代碼如下:
# -*- coding:utf-8 -*-
import numpy as np
'''
輸入的data的shape=(627,652)
'''
def write_to_nc_canque(data,file_name_path):
import netCDF4 as nc
lonS=np.linspace(119.885,120.536,652)
latS=np.linspace(29.984,29.358,627)
da=nc.Dataset(file_name_path,'w',format='NETCDF4')
da.createDimension('lons',652) #創(chuàng)建坐標點
da.createDimension('lats',627) #創(chuàng)建坐標點
da.createVariable("lon",'f',("lons")) #添加coordinates 'f'為數(shù)據(jù)類型,不可或缺
da.createVariable("lat",'f',("lats")) #添加coordinates 'f'為數(shù)據(jù)類型,不可或缺
da.variables['lat'][:]=latS #填充數(shù)據(jù)
da.variables['lon'][:]=lonS #填充數(shù)據(jù)
da.createVariable('u','f8',('lats','lons')) #創(chuàng)建變量,shape=(627,652) 'f'為數(shù)據(jù)類型,不可或缺
da.variables['u'][:]=data #填充數(shù)據(jù)
da.close()
write_to_nc_canque(one,'D://new.nc')
'''
輸入的data的shape=(627,652)
'''
def write_to_nc_wanmei(data,file_name_path):
import netCDF4 as nc
lonS=np.linspace(119.885,120.536,652)
latS=np.linspace(29.984,29.358,627)
da=nc.Dataset(file_name_path,'w',format='NETCDF4')
da.createDimension('lon',652) #創(chuàng)建坐標點
da.createDimension('lat',627) #創(chuàng)建坐標點
da.createVariable("lon",'f',("lon")) #添加coordinates 'f'為數(shù)據(jù)類型,不可或缺
da.createVariable("lat",'f',("lat")) #添加coordinates 'f'為數(shù)據(jù)類型,不可或缺
da.variables['lat'][:]=latS #填充數(shù)據(jù)
da.variables['lon'][:]=lonS #填充數(shù)據(jù)
da.createVariable('u','f8',('lat','lon')) #創(chuàng)建變量,shape=(627,652) 'f'為數(shù)據(jù)類型,不可或缺
da.variables['u'][:]=data #填充數(shù)據(jù)
da.close()
write_to_nc_wanmei(one,'D://new1.nc')
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python二進制數(shù)據(jù)結構Struct的具體使用
在C/C++語言中,struct被稱為結構體。而在Python中,struct是一個專門的庫,用于處理字節(jié)串與原生Python數(shù)據(jù)結構類型之間的轉換。本文就詳細介紹struct的使用方式2021-06-06

