简体   繁体   English

python 多维数组的平均值.netcdf plot

[英]python average of multidimensional array netcdf plot

I read a multidimensional array from.netCDF file.我从 .netCDF 文件中读取了一个多维数组。 The variable that I need to plot is named "em", and it has 4 dimensions ´em (years, group, lat, lon)´我需要 plot 的变量名为“em”,它有 4 个维度“em(年、组、纬度、经度)”

The "group" variable has 2 values, I am interested only of the first one. “group”变量有两个值,我只对第一个感兴趣。 So the only variable that I need to manage is the "years" variable.所以我需要管理的唯一变量是“年”变量。 The variable "years" has 17 values.变量“years”有 17 个值。 For the first plot I need to average the first 5 years, and for the second plot I have to aveage from 6th years to the last years.对于第一个 plot,我需要对前 5 年进行平均,对于第二个 plot,我必须对第 6 年到最后几年进行平均。

data = Dataset (r'D:\\Users\\file.nc') 
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
year = data.variables['label'][:]
group  = data.variables['group'][:] 
em= data.variables['em'][:]

How can I create a 2 dimensional array avareging for this array?如何为这个数组创建一个二维数组 avareging? First one:第一:

`em= data.variables['em'][0:4][0][:][:]`

Second one:第二个:

em= data.variables['em'][5:16][0][:][:]

I create a simple loop我创建了一个简单的循环

nyear=(2005-2000)+1
for i in range (nyear):
    em_1= data.variables['em'][i][0][:][:]
    em_1+=em_1
em_2000_2005=em_1/nyear

but I think there could be more elegant easy way to this on python但我认为在 python 上可能有更优雅的简单方法

I would highly recommend using xarray for working with NetCDF files.我强烈建议使用xarray来处理 NetCDF 文件。 Rather than keeping track of indices positionally, you can operate on them by name which greatly improves code readability.您可以按名称对索引进行操作,而不是按位置跟踪索引,这大大提高了代码的可读性。 In your example all you would need to do is在您的示例中,您需要做的就是

import xarray as xr

ds = xr.open_dataset(r'D:\\Users\\file.nc')
em_mean1 = ds.em.isel(label = range(6,18)).mean()
em_mean2 = ds.em.isel(label = range(6)).mean()

the .isel method selects the indices of the specified dimension (label in this case), and the .mean() method computes the average over the selection. .isel方法选择指定维度(在本例中为标签)的索引,.mean ()方法计算选择的平均值。

You can use NumPy:您可以使用 NumPy:

em = data.variables['em'][:];
em_mean = np.mean(em,axis=0) # if you want to average all over first dimension

If data contains NaN's, just use NumPY's nanmean.如果数据包含 NaN,只需使用 NumPY 的 nanmean。

As you wanted to average first 3 values, for the first case, use:由于您想平均前 3 个值,对于第一种情况,请使用:

em_mean1 = np.squeeze(np.mean(em[0:4,:],axis=0)) 

and take for the plot:并取 plot:

em_mean1 = np.squeeze(em_mean1[0,:]);

You can do similar for the second case.你可以对第二种情况做类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM