组合了大量的netCDF文件

时间:2015-03-09 22:51:48

标签: python netcdf

我有一个netCDF(.nc)文件的大文件夹,每个文件都有一个相似的名字。数据文件包含时间,经度,纬度和月降水量的变量。目标是使每个月的平均月降水量超过X年。因此,最后我将得到12个值,表示每个纬度和长度的X年平均月降水量。多年来,每个文件都是同一个位置。 每个文件都以相同的名称开头,以“date.sub.nc”结尾,例如:

'data1.somthing.somthing1.avg_2d_Ind_Nx.200109.SUB.nc'
'data1.somthing.somthing1.avg_2d_Ind_Nx.200509.SUB.nc'
'data2.somthing.somthing1.avg_2d_Ind_Nx.201104.SUB.nc'
'data2.somthing.somthing1.avg_2d_Ind_Nx.201004.SUB.nc'
'data2.somthing.somthing1.avg_2d_Ind_Nx.201003.SUB.nc'
'data2.somthing.somthing1.avg_2d_Ind_Nx.201103.SUB.nc'
'data1.somthing.somthing1.avg_2d_Ind_Nx.201203.SUB.nc'

结尾是YearMonth.SUB.nc 到目前为止我所拥有的是:

array=[]
f = nc.MFDataset('data*.nc')
precp = f.variables['prectot']
time = f.variables['time']
array = f.variables['time','longitude','latitude','prectot'] 

我得到一个KeyError :('时间','经度','纬度','prectot')。有没有办法结合所有这些数据,所以我能够操纵它?

3 个答案:

答案 0 :(得分:5)

正如@CharlieZender所提到的,ncra是这里的方法,我将提供有关将该功能集成到Python脚本中的更多细节。 (PS - 您可以使用Homebrew轻松安装NCO,例如http://alejandrosoto.net/blog/2014/01/22/setting-up-my-mac-for-scientific-research/

import subprocess
import netCDF4
import glob
import numpy as np

for month in range(1,13):
    # Gather all the files for this month
    month_files = glob.glob('/path/to/files/*{0:0>2d}.SUB.nc'.format(month))


    # Using NCO functions ---------------
    avg_file = './precip_avg_{0:0>2d}.nc'.format(month)

    # Concatenate the files using ncrcat
    subprocess.call(['ncrcat'] + month_files + ['-O', avg_file])

    # Take the time (record) average using ncra 
    subprocess.call(['ncra', avg_file, '-O', avg_file])

    # Read in the monthly precip climatology file and do whatever now
    ncfile = netCDF4.Dataset(avg_file, 'r')
    pr = ncfile.variables['prectot'][:,:,:]
    ....

    # Using only Python -------------
    # Initialize an array to store monthly-mean precip for all years
    # let's presume we know the lat and lon dimensions (nlat, nlon)
    nyears = len(month_files)
    pr_arr = np.zeros([nyears,nlat,nlon], dtype='f4')

    # Populate pr_arr with each file's monthly-mean precip
    for idx, filename in enumerate(month_files):
        ncfile = netCDF4.Dataset(filename, 'r')
        pr = ncfile.variable['prectot'][:,:,:]  
        pr_arr[idx,:,:] = np.mean(pr, axis=0)
        ncfile.close()

    # Take the average along all years for a monthly climatology
    pr_clim = np.mean(pr_arr, axis=0)  # 2D now [lat,lon]

答案 1 :(得分:3)

NCO使用

执行此操作
ncra *.01.SUB.nc pcp_avg_01.nc
ncra *.02.SUB.nc pcp_avg_02.nc
...
ncra *.12.SUB.nc pcp_avg_12.nc
ncrcat pcp_avg_??.nc pcp_avg.nc

当然,前12个命令可以使用Bash循环完成,将总行数减少到少于5。如果您更喜欢使用python编写脚本,可以使用它来检查您的答案。 ncra docs here

答案 2 :(得分:0)

命令 ymonmean 计算CDO中日历月的平均值。因此,任务可以分为两行:

cdo mergetime data*.SUB.nc  merged.nc  # put files together into one series
cdo ymonmean merged.nc annual_cycle.nc # mean of all Jan,Feb etc. 

cdo还可以计算其他统计数据的年度周期,ymonstd,ymonmax等...时间单位可以是天数或五进制数以及月数。 (例如ydaymean)。