0

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 calcPfunction.

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'>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.