簡體   English   中英

在python中讀取和操作多個netcdf文件

[英]Reading and manipulating multiple netcdf files in python

我需要幫助閱讀多個netCDF文件,盡管這里沒有幾個例子,但它們都沒有正常工作。 我正在使用Python(x,y)vers 2.7.5和其他軟件包:netcdf4 1.0.7-4,matplotlib 1.3.1-4,numpy 1.8,pandas 0.12,basemap 1.0.2 ......

我用GrADS做的事情很少,我需要在Python中開始做它們。 我有幾個2米溫度數據(每年4小時數據,來自ECMWF),每個文件包含2米臨時數據,Xsize = 480,Ysize = 241,Zsize(水平)= 1,Tsize(時間)=閏年為1460或1464。 這些是我的文件名相似:t2m.1981.nc,t2m.1982.nc,t2m.1983.nc ......等。

基於這個頁面:( 循環通過netcdf文件和運行計算 - Python或R )這是我現在的位置:

from pylab import *
import netCDF4 as nc
from netCDF4 import *
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

f = nc.MFDataset('d:/data/ecmwf/t2m.????.nc') # as '????' being the years
t2mtr = f.variables['t2m']

ntimes, ny, nx = shape(t2mtr)
temp2m = zeros((ny,nx),dtype=float64)
print ntimes
for i in xrange(ntimes):
    temp2m += t2mtr[i,:,:] #I'm not sure how to slice this, just wanted to get the 00Z values.
      # is it possible to assign to a new array,...
      #... (for eg.) the average values of  00z for January only from 1981-2000? 

#creating a NetCDF file
nco = nc.Dataset('d:/data/ecmwf/t2m.00zJan.nc','w',clobber=True)
nco.createDimension('x',nx)
nco.createDimension('y',ny)

temp2m_v = nco.createVariable('t2m', 'i4',  ( 'y', 'x'))
temp2m_v.units='Kelvin'
temp2m_v.long_name='2 meter Temperature'
temp2m_v.grid_mapping = 'Lambert_Conformal' # can it be something else or ..
#... eliminated?).This is straight from the solution on that webpage.

lono = nco.createVariable('longitude','f8')
lato = nco.createVariable('latitude','f8')
xo = nco.createVariable('x','f4',('x')) #not sure if this is important
yo = nco.createVariable('y','f4',('y')) #not sure if this is important
lco = nco.createVariable('Lambert_Conformal','i4') #not sure

#copy all the variable attributes from original file
for var in ['longitude','latitude']:
    for att in f.variables[var].ncattrs():
        setattr(nco.variables[var],att,getattr(f.variables[var],att))

# copy variable data for lon,lat,x and y
lono=f.variables['longitude'][:]
lato=f.variables['latitude'][:]
#xo[:]=f.variables['x']
#yo[:]=f.variables['y']

#  write the temp at 2 m data
temp2m_v[:,:]=temp2m

# copy Global attributes from original file
for att in f.ncattrs():
    setattr(nco,att,getattr(f,att))

nco.Conventions='CF-1.6' #not sure what is this.
nco.close()

#attempt to plot the 00zJan mean
file=nc.Dataset('d:/data/ecmwf/t2m.00zJan.nc','r')
t2mtr=file.variables['t2m'][:]
lon=file.variables['longitude'][:]
lat=file.variables['latitude'][:]
clevs=np.arange(0,500.,10.)
map =   Basemap(projection='cyl',llcrnrlat=0.,urcrnrlat=10.,llcrnrlon=97.,urcrnrlon=110.,resolution='i')
x,y=map(*np.meshgrid(lon,lat))
cs = map.contourf(x,y,t2mtr,clevs,extend='both')
map.drawcoastlines()
map.drawcountries()
plt.plot(cs)
plt.show()

第一個問題是在temp2m += t2mtr[1,:,:] 我不確定如何切割數據以獲得所有文件的00z(僅限1月)。

第二,在運行測試時, cs = map.contourf(x,y,t2mtr,clevs,extend='both')稱“形狀與z的形狀不匹配:找不到(1,1)而不是( 241480)”。 我知道輸出數據可能有一些錯誤,因為記錄值時出錯,但我無法弄清楚是什么/在哪里。

謝謝你的時間。 我希望這不會令人困惑。

所以t2mtr是一個3d數組

ntimes, ny, nx = shape(t2mtr)

這會將第1軸上的所有值相加:

for i in xrange(ntimes):
    temp2m += t2mtr[i,:,:]

更好的方法是:

temp2m = np.sum(tm2tr, axis=0)
temp2m = tm2tr.sum(axis=0) # alt

如果你想要平均值,請使用np.mean而不是np.sum

要平均時間子集jan_times ,請使用如下表達式:

jan_avg = np.mean(tm2tr[jan_times,:,:], axis=0)

如果您只想要一個簡單的范圍,例如前30次,這是最簡單的。 為簡單起見,我假設數據是每日,而年份是恆定長度。 你可以調整4小時頻率和閏年。

tm2tr[0:31,:,:]

獲得Jan數據幾年的簡單方法是構建一個索引,如:

yr_starts = np.arange(0,3)*365 # can adjust for leap years
jan_times = (yr_starts[:,None]+ np.arange(31)).flatten()
# array([  0,   1,   2, ...  29,  30, 365, ..., 756, 757, 758, 759, 760])

另一個選擇是重塑tm2tr (閏年不適用)。

tm2tr.reshape(nyrs, 365, nx, ny)[:,0:31,:,:].mean(axis=1)

您可以使用以下內容測試時間采樣:

np.arange(5*365).reshape(5,365)[:,0:31].mean(axis=1)

數據集是否有時間變量? 您可以從中提取所需的時間索引。 我在幾年前使用ECMWF數據,但不記得很多細節。

至於你的contourf錯誤,我會檢查3個主要參數的形狀: xyt2mtr 他們應該匹配。 我還沒有使用過Basemap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM