根据垂直级别合并多个 Netcdf 文件

Merging multiple Netcdf files according to the vertical level

我有 34 个 netCDF (nc) 文件,其中包含纬度、经度和每个文件中的数据。每个文件名都包含一个与 hPa 中的压力级别相对应的数字(从 1 到 34,对应的压力级别从(1000 hPa 到 0.4 hPa)。我想将所有文件加入一个具有此垂直级别维度信息的 nc 文件。

我尝试使用 xarray open_mfdataset 读取整个文件,但我无法 con_cat 使用级别维度,因为它不在文件中。

import xarray as xr
ds = xr.open_mfdataset('/media/MediaCentre/Dataset/d9/data*.nc',concat_dim='level')

文件在全局属性中没有任何关于压力的信息。它们的名称顺序为:data1.nc、data2.nc、... dataN.nc 并对应于以下压力水平 (hPa): 1000 975 950 925 900 850 800 750 700 650 600 550 500 450 400 350 300 *250 200 150 100 70 50 40 30 20 15 10 7 5 3 2 1 0.4

如何使用 python xarray 或 cdo/nco 将它们合并在一起?

样本数据在这里https://www.dropbox.com/sh/linfn0721ze3j1f/AACwxTsQVNyiE7mF_gRbpRfra?dl=0

使用 CDO 可能更容易做到这一点。以下将合并您提供的两个示例文件:

cdo -L -merge -setlevel,0.4 data1.nc -setlevel,1 data2.nc merged.nc

只需修改以上内容即可处理所有文件。

这是一个BASH脚本,它定义了一个压力级别列表(看评论),然后主力是ncap2,它用于添加一个名为“level”的维度每个文件,然后用定义的压力值定义一个变量“level”。然后我使用 ncatted 添加属性以确保完整性,例如压力单位。

然后在最后使用

cdo 来合并文件(也可以使用 nco)。这里的例子只合并了两个文件,但是你可以合并你所有的 .

#!/bin/bash

# define pressure levels here, start, inc, end or just a list
# this is important to get right, the number of files processed
# depends on this list, here I only process 2 files,
# data1.nc = 1000hPa, data2.nc=975 hPa

# this was my test merging two files, can use seq if p levs are regular
# p_levs=($(seq 1000 -25 975))

# this is the full code:
p_levs=(1000 975 950 925 900 850 800 750 700 650 600 550 500 450 400 350 300 250 200 150 100 70 50 40 30 20 15 10 7 5 3 2 1 0.4)
    
# loop over the pressure levels, data1.nc-> first pressure level, data2-> second etc
for i in ${!p_levs[@]} ; do
    infile=data$(expr $i + 1).nc # nc filename

    # add a level dimension and define variable with pressure level:
    ncap2 -O -s 'defdim("level",1);q[level,lat,lon]=q;level=array('${p_levs[$i]}',10,$level)' $infile tmp${i}_$infile

    # put in attributes for the new level variable:
    ncatted -h -a units,"level",o,c,"hPa" tmp${i}_$infile
    ncatted -h -a long_name,"level",o,c,"Pressure level" tmp${i}_$infile
done

# merge the files:
cdo merge tmp*.nc merged.nc

# clean up tmp files at end 
rm -f tmp*.nc 

我使用 p_levs="1000 975" 对其进行了测试,它合并了前两个文件 data1.nc 和 data2.nc 没有问题,生成的文件在 ncview 中打开正常,看起来不错。

注意:出于某种原因,ncap2 正在从“q” , I'm not sure why, so it means you will need to readd those with ncatted. 中删除属性以构建此代码。

NCO 的另一种方法是首先将级别与 ncecat 结合,例如,

ncecat -u level in*.nc out1.nc

然后用ncap2加上水平坐标,例如

ncap2 -O -s 'level[$level]={1000, 975, ... 0.4}' out1.nc out2.nc

然后添加带有 ncatted 的属性,如 Adrian 所示。

ncatted <Adrian's example> out2.nc out3.nc

祝你好运, 查理