在python中读取和操作多个netcdf文件

2024-10-01 15:39:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要阅读多个netCDF文件的帮助,尽管这里有几个例子,但它们都不能正常工作。 我使用的是Python(x,y)版本2.7.5和其他软件包:netcdf4 1.0.7-4、matplotlib 1.3.1-4、numpy 1.8、pandas 0.12, 基础地图1.0.2。。。在

我有一些习惯于用Python来做毕业生的事情。 我有一些2米的温度数据(每年4小时的数据,来自ECMWF),每个文件包含2米的温度数据,Xsize=480,Ysize=241, Zsize(级别)=1,Tsize(时间)=1460或1464(闰年)。 这些是我的文件名看起来很像:t2m.1981.nc,t2m.1982.nc,t2m.1983.nc…等等

根据本页: (Loop through netcdf files and run calculations - Python or 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:found(1,1)而不是(241480)的形状不匹配”。我知道输出数据可能有一些错误,因为记录值时出错,但我不知道是什么/在哪里。在

谢谢你的时间。我希望这不会让人困惑。在


Tags: the数据fromimportmapfordatavariables
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:37

所以t2mtr是一个3d数组

ntimes, ny, nx = shape(t2mtr)

这将对第一个轴上的所有值求和:

^{pr2}$

更好的方法是:

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次。为了简单起见,我假设数据是每天的,年份是固定长度的。你可以调整4hr频率和闰年。在

tm2tr[0:31,:,:]

获取几年1月数据的一种简单方法是构建一个指数,如:

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合作过。在

相关问题 更多 >

    热门问题