Мне нужна помощь в чтении нескольких файлов netCDF, несмотря на несколько примеров здесь, ни один из них не работает должным образом. Я использую Python(x,y) версии 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 (скажем, только за январь) всех файлов.
Во-вторых, во время выполнения теста на cs = map.contourf(x,y,t2mtr,clevs,extend='both')
возникла ошибка, говорящая: «Форма не соответствует форме z: найдено (1,1) вместо (241 480)». Я знаю некоторую ошибку, вероятно, в выходных данных из-за ошибки при записи значений, но я не могу понять, что/где.
Спасибо за ваше время. Надеюсь, это не сбивает с толку.