mtnez / netcdf4-python

Automatically exported from code.google.com/p/netcdf4-python
Other
0 stars 0 forks source link

modifying netcdf4 variables in an existing netcdf4 file. #109

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
This is not so much a problem in the netCDF4 module per se. I've read the 
documentation and I'm fairly new to python so these examples set the bar quite 
high to begin with.
I understand how to read the data and the writing of the data is still misty 
for me. Anyway I learn by doing and here is what I tried to do:

1. I read in a netcdf4 file that I created in C:
rgrp = netCDF4.Dataset('ODIN_NWP_2001_01_01_00.NC','r+')
It is unclear from the explanation of 'r+' that this allows me to modify 
existing variables.

2. Then I extracted the variable that I need to modify/replace:
pv = rgrp.groups['Data_3D'].variables['PV']

3. Here is where it gets tricky. "pv" is now a netcdf.variable. It doesn't 
allow me to operate on it (+, -, *, /, etc.) How do I do this and then write 
the variable back to the file?
I've tried pv = pv*2 but this fails.

What is the expected output? What do you see instead?
print pv
<type 'netCDF4.Variable'>
float32 PV(u'level', u'lat', u'lon')
    longname: Potential Vorticity
    _FillValue: -999.0
    units: K m**2 kg**-1 s**-1
    code: 60
    scale_factor: 1.0
    add_offset: 0.0
path = /Data_3D
unlimited dimensions = ()
current size = (60, 181, 360)

pv = pv*2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/marstonjohnston/Desktop/<ipython-input-8-31918f32d50b> in <module>()
----> 1 pv = pv*2
TypeError: unsupported operand type(s) for *: 'netCDF4.Variable' and 'int'

I'm using the latest version of netCDF4 within python 2.7 on a Mac Lion.
I suspect that a large part of the problem is that much of the inner workings 
of the module is hidden and I just need some examples to get me going. 

I hope this is enough information and I do appreciate any help with this. I can 
do this in C but I have hundreds of files to modify and python is a easier 
method than C - I think. 

Original issue reported on code.google.com by shejo...@gmail.com on 21 Feb 2012 at 1:38

GoogleCodeExporter commented 9 years ago
To actually read the data from the netCDF variable object pv, you have to slice 
it (see section 6 of the docs).  pv[:] reads all the data.

So, 

pvsq = pv[:]**2
pv[:] = pvsq

should do what you want.

Original comment by whitaker.jeffrey@gmail.com on 21 Feb 2012 at 2:03

GoogleCodeExporter commented 9 years ago
Thanks. It was not clear that without a write statement the variable was 
written to the file. Now I understand.

/M

Original comment by shejo...@gmail.com on 22 Feb 2012 at 7:40

GoogleCodeExporter commented 9 years ago

Original comment by whitaker.jeffrey@gmail.com on 26 Feb 2014 at 2:04