Skip to main content
 首页 » 编程设计

python之来自多个 netcdf 文件的混合层高度的 numpy.mean

2025年02月15日9zhwl

我知道如何计算一个 netcdf 文件中变量的平均值。但是,我有 40 个 netcdf 文件。在每个文件中,我有 4000 个混合层高度的数据值。我想为多个 netcdf 文件创建一个平均混合层高度列表。 最后我的列表的大小应该是 40。

有人可以帮我用 python 代码来创建这个列表吗? 非常感谢。

这是我用来计算单个 netcdf 文件中一层的平均混合层高度的代码

import numpy as np  
import netCDF4 
 
f = netCDF4.Dataset('niv.nc')  
 
 
#the shape of my data set is (5760,3)   
#5760 is the number of lists of time    
#In each list I have 3 mixing layer heights for 3 layers.   
#I'm going to call all the mixing layer height data for the first layer  
 
a= (f.variables['pbl'][:,0])   
print (np.mean(a)) 

请您参考如下方法:

您必须以某种方式获取文件名列表。在这里,我假设您将所有文件都放在一个文件夹中,并且该文件夹中没有其他 netCDF 文件。为此,请使用 netCDF4 并要求每个文件都有一个单独的平均值

import numpy as np 
import netCDF4 
from glob import glob 
 
# you want to modify this to use your actual data directory 
filename_list = glob('/home/user/data_dir/*.nc') 
 
mean_list = [] 
for filename in filename_list:  # make filename_list with something like os.listdir 
    with netCDF4.Dataset(filename) as ds: 
        mean_list.append(np.mean(ds.variables['pbl'][:, 0])) 

用 xarray 做同样的事情:

import xarray as xr 
from glob import glob 
 
# you want to modify this to use your actual data directory 
filename_list = glob('/home/user/data_dir/*.nc') 
 
mean_list = [] 
for filename in filename_list:  # make filename_list with something like os.listdir 
    with xr.open_dataset(filename) as ds: 
        mean_list.append(np.mean(ds['pbl'][:, 0].values)) 

如果不是获取每个文件的平均值,假设第一个维度是时间,并且您想获取所有 文件的平均值。要使用 xarray 做到这一点,您可以像这样使用 open_mfdataset:

import xarray as xr 
import os 
from glob import glob 
 
# you want to modify this to use your actual data directory 
filename_list = glob('/home/user/data_dir/*.nc') 
 
ds = xr.open_mfdataset(filename_list, concat_dim='time') 
mean = np.mean(ds['pbl'][:, 0].values)