pygrib-2.0.3/docs/index.html
導入pygrib模塊
>>> import pygrib
打開grib文件,獲取grib消息迭代器
>>> grbs = pygrib.open('sampledata/flux.grb')
和打開正常的python文件對象一樣,pygrib使用seek, tell, read, readline, 和close方法打開grib文件。唯一的不同的是,偏移量用grib消息衡量,而不是用字節。
>>> grbs.seek(2) >>> grbs.tell() 2 >>> grb = grbs.read(1)[0] # read returns a list with the next N (N=1 in this case) messages. >>> grb # printing a grib message object displays summary info 3:Maximum temperature:K (instant):regular_gg:heightAboveGround:level 2 m:fcst time 108-120 hrs:from 200402291200 >>> grbs.tell() 3
輸出文件清單:
>>> grbs.seek(0) >>> for grb in grbs: >>> grb 1:Precipitation rate:kg m**-2 s**-1 (avg):regular_gg:surface:level 0:fcst time 108-120 hrs (avg):from 200402291200 2:Surface pressure:Pa (instant):regular_gg:surface:level 0:fcst time 120 hrs:from 200402291200 3:Maximum temperature:K (instant):regular_gg:heightAboveGround:level 2 m:fcst time 108-120 hrs:from 200402291200 4:Minimum temperature:K (instant):regular_gg:heightAboveGround:level 2 m:fcst time 108-120 hrs:from 200402291200
尋找匹配名字的第一個grib消息
>>> grb = grbs.select(name='Maximum temperature')[0]
使用'values'鍵提取數據值(grb.keys()將會返回一個可用鍵的序列)
# The data is returned as a numpy array, or if missing values or a bitmap # are present, a numpy masked array. Reduced lat/lon or gaussian grid # data is automatically expanded to a regular grid. Details of the internal # representation of the grib data (such as the scanning mode) are handled # automatically. >>> maxt = grb.values # same as grb['values'] >>> maxt.shape, maxt.min(), maxt.max() (94, 192) 223.7 319.9
獲取網格經緯度值
>>> lats, lons = grb.latlons() >>> lats.shape, lats.min(), lats.max(), lons.shape, lons.min(), lons.max() (94, 192) -88.5419501373 88.5419501373 0.0 358.125
獲取第二個消息
>>> grb = grbs.message(2) # same as grbs.seek(1); grb=grbs.readline() >>> grb 2:Surface pressure:Pa (instant):regular_gg:surface:level 0:fcst time 120 hrs:from 200402291200
從北美洲子集中提取數據,得到經緯值
>>> data, lats, lons = grb.data(lat1=20,lat2=70,lon1=220,lon2=320) >>> data.shape, lats.min(), lats.max(), lons.min(), lons.max() (26, 53) 21.904439458 69.5216630593 221.25 318.75
使用存在的鍵(或者通過屬性或者訪問字典)修改值
>>> grb['forecastTime'] = 240 >>> grb.dataDate = 20100101
得到與編碼信息相關的二進制字符串
>>> msg = grb.tostring() >>> grbs.close() # close the grib file
將修改的信息寫到新GRIB文件中
>>> grbout = open('test.grb','wb') >>> grbout.write(msg) >>> grbout.close() >>> pygrib.open('test.grb').readline() 1:Surface pressure:Pa (instant):regular_gg:surface:level 0:fcst time 240 hrs:from 201001011200 Documentation
============================================
注意!
select方法為從文件中,提取gribmessage對象的集合到一個列表的方法。得到的結果為一個列表(List對象),不能之前對其求keys屬性。只能對單個gribmessage對象求屬性!
可行的方法是打開這個List,對其中每一個元素(gribmessage對象)進行循環,分別求keys
gribmessage可以求values
index對象的slect方法比pygrib.open 對象的slect方法快,但只是適用於單變量場
findex = pygrib.index(fname,'level','month','day') # 獲取messags索引
selected_messages = findex.select(level=lev,month=month,day=day) # “天選之消息”
注意:findex.select()括號中的關鍵字必須要和包含前面定義用到的所有關鍵字,否則會出現錯誤