0

I have a netCDF file and was trying to create new variables using python netCDF4. However the program failed to assign values into the array.

Below is my code

import netCDF4
file = netCDF4.Dataset(filename, "r+")
tmp = file.createVariable("tmp", "f4", ('time','height','lat','lon'), zlib=True)
tmp.set_auto_mask(False)
tmp.set_auto_maskandscale(False)

//setting values 
tmp[0][0][0][0] = 0.1234
print(tmp[0][0][0][0])
//I got 9.96921e+36, which seems to be the default fill value

What should I do to solve this problem?

Any help would be appreciated.

TIA

Henry Lau
  • 1
  • 7

1 Answers1

0

Accessing variables that are in a NetCDF file is done like this:

file.variables["tmp"][0,0,0,0] = 0.1234
//read complete var
putDataInHere = file.variables["tmp"][:]

If you look at the tmp variable and print it you will see something like this:

<type "netCDF4._netCDF4.Variable">
float32 temp(time, level, lat, lon)
    least_significant_digit: 3
    units: K
unlimited dimensions: time, level
current shape = (0, 0, 73, 144)
lpoorthuis
  • 111
  • 4
  • So if I want to assign a new value to the location, I do 'file.variable["tmp"][0,0,0,0] = 0.1234' instead of 'file.variable["tmp"][0][0][0][0] = 0.1234' right? I tried just now and seems like it works. @lpoorthuis – Henry Lau Apr 19 '17 at 17:24
  • exactly. take a look at [numpy indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html). python netcdf4 is using numpy arrays so the indexing is a bit different then native python lists – lpoorthuis Apr 19 '17 at 17:29
  • I see. It works smoothly now. Thanks for the help. @lpoorthuis – Henry Lau Apr 19 '17 at 17:31