Inspired by https://stackoverflow.com/a/55001336/7474503 I try to apply a function on my 3d netCDF/ numpy array.
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()
Unfortunately I receive an IndexError : Index cannot be multidimensional
Does anyone have an idea what could be the reason? I already tried different indeces of the shape and different orders of the variable for the calcP
function.
Here some more information about my variables:
Output:
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'>
I think your a
and b
should be numpy arrays, not netCDF4.Variable
. So,
a = fh.variables['a'][:]
b = fh.variables['b'][:]
Also I think you might need to set dtype=int
in the 2nd last line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.