Python:将函数应用于netCDF / numpy 3d数组中的每个条目

问题描述 投票:0回答:1

https://stackoverflow.com/a/55001336/7474503的启发,我尝试在我的3d netCDF / numpy数组上应用一个函数。

from netCDF4 import Dataset 
import numpy as np
my_example_nc_file = '/Users/Severin/Desktop/ecmwf_era5_17010100.nc'
fh = Dataset(my_example_nc_file, mode='r') #fh becomes the file handle of the open netCDF file

lons = fh.variables['lon'][:]
lats = fh.variables['lat'][:]
gph = fh.variables['GPH'][0,:,:,:]

# Function to calculate the Pressure in hPa at point x/y at level z
# p(z,j,i) = a(z) + b(z)*ps(j,i)
# http://cfconventions.org/Data/cf-conventions/cf-conventions-1.0/build/apd.html
# Assumption j,i are lat & lon (in this order)
# lat=y=j & lon=x=i
def calcP(z,x,y,a=a,b=b,ps=ps):
    p = (a[z]+b[z]*ps[x,y])/100
    return p

a = fh.variables['a']
b = fh.variables['b']
ps = fh.variables['ps'][0,:,:]

p3d = np.fromfunction(calcP, (137,601,1200), a=a,b=b,ps=ps, dtype=float)
fh.close()

不幸的是我收到了一个IndexError:索引不能是多维的

有谁知道可能是什么原因?我已经尝试了calcP函数的形状和变量的不同顺序的不同索引。

这里有一些关于我变量的更多信息:

输出:

gph shape: (137, 601, 1200)
gph type: <class 'numpy.ma.core.MaskedArray'>
ps shape (601, 1200)
ps type: <class 'numpy.ma.core.MaskedArray'>
ps mask: False
a shape: (137,)
a type: <class 'netCDF4._netCDF4.Variable'>
b shape: (137,)
b type: <class 'netCDF4._netCDF4.Variable'>
python arrays numpy netcdf
1个回答
1
投票

我认为你的ab应该是numpy数组,而不是netCDF4.Variable。所以,

a = fh.variables['a'][:]
b = fh.variables['b'][:]

另外我想你可能需要在最后一行设置dtype=int

© www.soinside.com 2019 - 2024. All rights reserved.