0

I am doing a number of calculations on a timeseries of data and want to create a 2d netcdf file with the results of those calculations.

However, when saving the calculated values in the new array I get the following message:

IndexError: too many indices for array.

I am using python 3.6 with the NetCDF4 and numpy libraries.

val_list=[]
av_array=[]
#create netcdf
out_file=netCDF4.Dataset("test.nc","w", format="NETCDF4")
tempgrp=out_file.createGroup(var)
tempgrp.createDimension('lon', 575)
tempgrp.createDimension('lat', 541)
tempgrp.createDimension('time', None)
            
longitude = tempgrp.createVariable('Longitude', 'f4', 'lon')
latitude = tempgrp.createVariable('Latitude', 'f4', 'lat')  
temp = tempgrp.createVariable(var, 'f4', ('time', 'lon', 'lat'))
time = tempgrp.createVariable('Time', 'i4', 'time')
          
longitude[:] = 575
latitude[:] = 541

for i in range(540):
    for j in range(574):
                del val_list
                val_list=[]
                for t in range(30):
                    #create list of i,j coordinate
                    val_list.append(data[t,0,i,j])
                    #calculations
                av=sum(val_list)/float(len(val_list))#example
                temp[0,j,i] = av #this is where the error occurs

This is the output of print(temp):

<class 'netCDF4._netCDF4.Variable'> float32 Chlx(time, lon, lat) path = /Chlx unlimited dimensions: time current shape = (0, 575, 541) filling on, default _FillValue of 9.969209968386869e+36 used

The idea is to in the end create a 3d array (that is why the time dimension is there).

Can anyone give me a hint to why I get this index error?

0

1 Answer 1

2

It turns out the netCDF4 library gets an index error if you try to insert a NaN value. I have some areas in the map that are on land and thus have no value. I avoided the issue by adding the following check:

if av == int:
 temp[0,j,i] = av
else:
 temp[0,j,i] = 9.969209968386869e+36

Now when av is a non value it is replaced by the fill value of the netCDF before iserting it. There might be a more ellegant solution but this seems to work for me.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.