PyNIO
Important announcement: NCAR has made the decision to adopt Python as the scripting language platform of choice for future development of analysis and visualization tools. As part of this decision, both NCL and PyNIO are being placed into maintenance mode. Please read this open letter to NCL users to understand what kind of impact this will have on the future of NCL and PyNIO. |
PyNIO is a Python package that allows read and/or write access to a variety of data formats using an interface modeled on netCDF. PyNIO is composed of a C library called libnio along with a Python module based on and with an interface similar to the Scientific.IO.NetCDF module written by Konrad Hinsen. The C library contains the same data I/O code used in NCL, a scripting language developed for analysis and visualization of geo-scientific data. Currently supported formats include:
- netCDF3 and netCDF 4 classic format (read/write)
- netCDF 4 non-classic format (read/write, 1.5.0 version only)
- GRIB 1 and GRIB 2 (read-only)
- HDF 4 (read/write for Scientific DataSets only)
- HDF 5 (read/write, 1.5.0 version only)
- HDF-EOS2 and HDF-EOS5 (read-only for Grid and Swath data only)
- CCM history files (read-only)
- OGR - Open Geospatial Consortium's Simple Feature formats (ESRI Shapefile, MapInfo, GMT, Tiger) (read-only)
More detailed information about PyNIO's support for these formats is available at Data Formats Supported by the PyNIO module.
PyNIO interfaces with the Python environment using the multi-dimensional array module, NumPy. The NumPy version used to build PyNIO is available as the value of the module-level attribute __array_module_version__. PyNIO supports an extended selection mechanism for specifying subsets of file variables using coordinate values. This facility also has support for interpolation, dimension reordering (transposition), and indirect selection via auxiliary 2D coordinate variables. For information about this feature see PyNIO Extended Selection.
Note that while the package name is PyNIO, the module name that is imported into a Python script is Nio.
Installation instructions
For more details on installing packages via "conda", see the download page.
You can download the latest version of PyNIO using conda. We recommend installing it to a separate environment:
conda create --name pynio_env --channel conda-forge pynio source activate pynio_env
Note, you can name the pynio_env environment whatever you like.
To quickly test if Nio installed correctly, you can print the version and inline documentation:
import Nio print Nio.__version__ print Nio.__doc__
Class NioFile: Access supported-format files for reading and/or writing
Constructor: open_file(filepath, mode='r', options=None, history='', format='')
- filepath
The full or relative path of a file with data in a supported format. The file path may contain a home directory indicator starting with "~". A filepath extension (a suffix consisting of the final characters following the last dot) indicates the expected format. The extension can be added to specify the format regardless of whether it is part of the actual filename. Valid extensions include:
.nc, .cdf, .netcdf, .nc3, .nc4 (classic)
(NetCDF).nc4
(NetCDF-4) (1.5.0 only).gr, .gr1, .grb, .grib, .grb1, .grib1, .gr2, .grb2, .grib2
(GRIB 1 and GRIB 2).hd, .h4, .hdf
(HDF).he2, .he4, .hdfeos
(HDF-EOS2).he5, .hdfeos5
(HDF-EOS5).h5, .hdf5
(HDF5) (1.5.0 only).ccm
(CCM history files).shp, .mif, .gmt, .rt1
(OGR Simple Feature formats, such as ESRI Shapefiles)
PyNIO handles these extensions in a case-insensitive manner:
.grib, .Grib, and .GRIB
all indicate a GRIB file.Rather than appending a format-specifying suffix to the actual filename, you may instead explicitly specify the file format using the optional argument format, described below.
- mode
This optional argument specifies the access mode. If not specified it defaults to 'r' -- read-only. PyNIO has three access modes, some of which can be specified in more than one way:
'r'
- Open an existing file for reading. PyNIO returns an error if the file does not exist. Attempts to modify the data will fail.
'w'
,'r+'
,'rw'
,'a'
- Open an existing file for modification or if the file does not exist create it. PyNIO returns an error if the file cannot be created because of file system access issues, or if a non-writable format is specified. Note that PyNIO never overwrites an existing file with an entirely new file.
'c'
- Create a file open for writing. PyNIO returns an error if the file exists, if the file cannot be created because of file system access issues, or if a non-writable format is specified.
- options
This optional argument must be an instance of the NioOptions class created prior to calling the
open_file
constructor. It is used to set a number of options that affect how the data is read and/or written.- history
This optional argument is a user-specified string that is appended to the global "history" attribute of a file that is opened for writing. If no "history" attribute currently exists in the file, it is created.
- format
This optional argument provides an alternate means of explicitly indicating the file format without the need to specify an artificial name for the data file. Instead of tacking on a suffix indicating the file format to the filepath argument, any valid extension documented under filepath, not including the initial period (.), may be supplied as the string value to the format argument. This argument or the tacked-on extension is only required if the file name itself does not end with a recognized extension. It can also be used in certain cases to handle a file as a different format than the extension indicates. For instance, HDF-EOS files often simply have an ".hdf" extension and can be read either as HDF or as HDF-EOS.
A NioFile object has the following standard attributes:
- dimensions
- This attribute is a dictionary with dimension names as keys and dimension lengths as values.
- variables
- This attribute is a dictionary with variable names as keys and the variable reference objects as values.
- attributes
- This attribute is a dictionary that contains the global attributes
associated with the file. It has the special property that its
contents are managed using the Python
getattr
andsetattr
methods. Currently it mirrors the contents of the "__dict__" attribute using a name ("attributes") that aligns with the terminology used by NetCDF. - __dict__
- This attribute is a dictionary that contains the global attributes
associated with the file. It has the special property that its
contents are managed using the Python
getattr
andsetattr
methods. Its use as the container of global file attributes is deprecated in favor of the "attributes" attribute.
- close(history='')
Closes the file. If the file was opened for writing, all buffers are flushed, ensuring the file is updated with all modifications. Any read or write access to the file or one of its variables after closing raises an exception. If the file is opened for writing, the optional argument history may be set with a string containing text to be appended to the global "history" attribute prior to closing the file. The "history" attribute will be created if it does not yet exist.
- create_dimension(name, length)
Creates a new dimension with the given name and length. length must be a positive integer or None, which stands for the unlimited dimension. Note that currently there can be only one unlimited dimension in a file.
- unlimited(name) (available in version 1.4.1 or later)
Returns True or False depending on whether the existing dimension with the given name is an unlimited (record) dimension. If True the dimension is unlimited, meaning that if the file is open for writing the dimension can be extended by writing to elements beyond the current size of the dimension.
- create_variable(name, type, dimensions)
Creates a new variable with the given name, type, and dimensions. The type is a 1 or 2 character string representing the type to be created. Note that only a subset of possible NumPy types can be created using the writable file formats currently supported by PyNIO. The dimensions argument must be a tuple containing dimension names that have been previously defined. A scalar variable is specified using an empty tuple.
The return value is the NioVariable object representing the new variable.
- set_option(name, value)
Sets certain options that can be modified after a NioFile instance has been created. Currently the only options that can be set using this method are MaskedArrayMode, ExplicitFillValues, MaskBelowValue, and MaskAboveValue.
Class NioOptions: Specify options
Constructor: options()
PyNIO enables you to specify a number of options that affect how data is read and/or written. Some are specific to a supported file format while others apply to all formats. No options need to be set for basic access to any of the supported file formats. There are several mechanisms for setting options. You can establish default option values that apply to all files subsequently opened during the execution of the script or the interactive session. This mechanism is discussed in the section option_defaults below. Conversely, using the NioFile method set_option, you can change certain options repeatedly after an open NioFile object has been created. However, the traditional method for setting options is to create an instance of the NioOptions class.
You create an
instance of the NioOptions class prior to calling the
NioFile constructor (open_file
). Define
attributes using the names of the options to be set along with their
desired values, and then pass the NioOptions instance
as the options argument to the NioFile constructor. All option
names and string-typed values are handled in a case-insensitive
manner. Options set in this manner override the values contained in
the option_defaults dictionary. The same
NioOptions instance can be used for multiple calls to
the NioFile constructor. There are a number of
format-specific options for NetCDF and GRIB files. In addition, there
are several options that apply generically to all formats.
Format-specific options
The format-specific options are documented along with the details of the interface to each supported format.Generic options
- FileStructure
- If this option is set to "advanced", then it allows you to read advance features like groups and compound data in NetCDF-4 and HDF5 files.
- ExplicitFillValues
- This option, whose default value is
None
, allows you to set a single value or a sequence of values that will be masked in any data that is returned from a NioVariable object into a masked array. If a sequence is specified, its first value is set as the fill_value attribute of the array. When this option is set to any value other thanNone
, the value of MaskedArrayMode is set to MaskedExplicit, meaning that any fill value attribute attached to the NioVariable will be ignored. This option can be set for an open NioFile instance, using the set_option method. - MaskAboveValue
- This option, whose default value is
None
, allows you to set a single value above which all values will be masked in any data that is returned from a NioVariable object into a masked array. However, if a value is also set for the MaskBelowValue option that is greater than the value set for MaskAboveValue, then the two values together define a range between which the values will be masked in the returned array. In any case, values specified using the ExplicitFillValues option are also masked. Setting this option to a value other thanNone
causes the value of MaskedArrayMode to be set to MaskedExplicit, meaning that any fill value attribute attached to the NioVariable will be ignored. This option can be set for an open NioFile instance, using the set_option method. - MaskBelowValue
- This option, whose default value is
None
, allows you to set a single value below which all values will be masked in any data that is returned from a NioVariable object into a masked array. However, if a value is also set for the MaskAboveValue option that is less that the value set for MaskBelowValue, then the two values together define a range between which the values will be masked in the returned array. In any case, values specified using the ExplicitFillValues option are also masked. Setting this option to a value other thanNone
causes the value of MaskedArrayMode to be set to MaskedExplicit, meaning that any fill value attribute attached to the NioVariable will be ignored. This option can be set for an open NioFile instance, using the set_option method. - MaskedArrayMode
- This option allows the user to control PyNIO's behavior with
respect to masked
arrays. There are four possible settings that control how
PyNIO decides whether to return a masked array or a
normal NumPy array:
- 'MaskedIfFillAtt' (default)
- Return a masked array if the file variable has a fill value attribute. The recognized fill value attributes are _FillValue and missing_value. The fill value is assigned to the MaskedArray fill_value attribute. missing_value is not used if _FillValue exists.
- 'MaskedAlways'
- Always return a masked array regardless of whether there is any fill value attribute.
- 'MaskedNever'
- Always return a normal NumPy array regardless of the existence of a fill value attribute.
- 'MaskedIfFillAttAndValue'
- Return a masked array only if there is a fill value attribute and the subset selected from the variable actually contains one or more elements equal to the fill value.
- 'MaskedExplicit'
- Ignore the fill value attributes associated with the file variable and only
masked values based on the set values of the options ExplicitFillValues,
MaskAboveValue, and MaskBelowValue. Any time any of
these options are set to a value other than
None
, MaskedArrayMode is automatically set to this value (although it may subsequently be given another value).
- UseAxisAttribute
- This boolean option applies only when extended selection syntax is
used for subscripting a PyNIO variable. By default it
is
False
. When setTrue
it specifies that if a coordinate variable associated with a dimension of the variable has the CF-compliant axis attribute, then its value must be used instead of the actual dimension name in the selection string. In order to be valid the axis attribute must have one of the values 'T', 'Z', 'Y', or 'X'. These values are CF-compliant shorthand usually representing the time, height, latitude, and longitude dimensions of a variable, although they can be used to identify other temporal-spatial coordinate systems as well. If the coordinate variables in a file have the axis attribute, then setting this optionTrue
allows you to specify an extended selection more compactly.
option_defaults
PyNIO now supplies a module-level dictionary called option_defaults that contains the names of all available options and their default values. Changing the value associated with an option name in the dictionary changes the default value that will apply for all subsequently opened files. You can retrieve the keys and values of this dictionary to discover the current default for any available option. Be aware, however, that if you set an option to an invalid value using this method, there will be no warning until the option's value is needed, generally upon opening a file that supports the option. Also note that if you access individual options by name using this method, the option names are not case-insensitive. They should be specified exactly as listed in the documentation above. However, string-valued option values are case-insensitive.Class NioVariable: Variable contained in a NioFile object
PyNIO creates a NioVariable object for each variable in the file when the open_file constructor is called. PyNIO also creates a NioVariable object when you call the create_variable method on a NioFile object for writing.
NioVariable objects behave much like array objects defined in the NumPy module, except that their data resides in a file. Subscripting a NioVariable using standard NumPy indexing syntax causes data to be read as a NumPy array. Assigning to a subscripted NioVariable causes data to be written if the file is open in write mode. You can access the complete contents of the variable using the [:] index notation or using the methods get_value and assign_value. An extended selection mechanism using a quoted string inside the selection brackets allows for the specification of variable subsets using coordinate variables associated with named dimensions in the file. This new mechanism supports transposition of dimensions based on the order of the named dimensions in the specification string, as well as interpolation to intermediate coordinate values, selection along an axis using a vector of coordinate values, and indirect specification using an intermediate multidimensional variable. For more information about the extended selection feature, see PyNIO Extended Selection.
NioVariable objects have the following standard attributes:
- rank
- This attribute is a scalar value indicating the number of dimensions in the variable.
- shape
- This attribute is a tuple containing the numbers of elements for each dimension in the same order as the dimensions themselves.
- dimensions
- This attribute is a tuple containing the names of the dimensions in order, left to right, of the slowest varying dimension to the fastest varying dimension.
- attributes
- This attribute is a dictionary containing the attributes associated with the
variable in the file. It has the special property that its
contents are managed using the Python
getattr
andsetattr
methods. Currently it mirrors the contents of the "__dict__" attribute using a name ("attributes") that aligns with the terminology used by NetCDF. Use of the "__dict__" attribute is deprecated. - __dict__
- This attribute is a dictionary containing the attributes
associated with the variable in the file. It has the special property
that its contents are managed using the Python
getattr
andsetattr
methods. Its use as the container of file variable attributes only is deprecated in favor of the "attributes" attribute.
Like the NioFile object attributes, these attributes should be considered read-only.
Methods:
- assign_value(value)
Assigns value to the variable. This method is the only way to assign values to scalar variables, which cannot be indexed. Otherwise, the method requires that all elements of the variable array be supplied, since there is no way of indicating a slice.
- get_value()
Returns the value of the variable. This method is the only way to access the value of scalar variables, which cannot be indexed.
- typecode()
Return the variable's type code.
Usage guide
This guide uses small snippets of sample code to document the basic capabilities of the PyNIO module. Operations that can be performed in read-only mode are listed first.Importing the module
import numpy as np import Nio
PyNIO requires the NumPy module to be installed in the Python distribution you are using, because it depends on its C API to implement its data array interface. Importing the NumPy interface provides many useful tools for manipulating NumPy arrays. Therefore it is recommended that you import NumPy into your Python script or interactive session. However, it is not required for the basic operations provided by PyNIO.To import the NumPy module using earlier verions of PyNIO:
import numpy as np import PyNIO_numpy.Nio as Nio
Open a supported-format file
The constructor for a NioFile object isopen_file
. It gathers all the essential metadata from the file and makes it available to the Python script.f = Nio.open_file("gribfile.grb")
Open a GRIB-formatted file in the current directory named either "gribfile.grb" or "gribfile" using the default read-only mode. Note that the extension ".grb" need not be present in the actual file name, but serves to indicate the expected format of the file. Since GRIB is a read-only format for PyNIO, this file could not be opened using any mode other than read-only.f = Nio.open_file("~/data/netcdffile.nc","c")
Create a new file called "netcdffile.nc" under the user's home directory in a directory called "data". This call will fail if a file with this name and path already exists.The other access modes ("w","rw","a","r+") all mean the same thing: open a file for writing. Do not overwrite an existing file, but allow modifications to it. Create a new file if it does not exist.
Open a supported-format file, setting options
opt = Nio.options() opt.PreFill = False opt.HeaderReserveSpace = 4000 f = Nio.open_file("netcdffile.nc","w",opt,"modified 2006/05/03")
Open a file called "netcdffile.nc" for writing in the current directory. If it does not exist create it. To improve performance, set the option for prefilling the elements of newly created variables to False. Also reserve 4000 additional bytes of space in the file header to hold new dimensions, variables, and/or attributes that are to be created. Finally, add a line to the global 'history' attribute.f = Nio.open_file("netcdffile.nc",options=opt,history="modified 2006/05/03",mode="w")
Alternate version of the previousopen_file
call using named arguments.Print a summary of the file contents
print f
Here is a sample print of a NetCDF file named "mars.nc":Nio file: mars.nc global attributes: title : 1 degree mars topography creation_date : Wed Mar 8 17:33:51 MST 2000 Conventions : COARDS dimensions: lon = 360 lat = 180 variables: float lon [ lon ] units : degrees_east long_name : longitude float lat [ lat ] units : degrees_north long_name : latitude float elev [ lat, lon ] units : meters long_name : median topography _FillValue : -99999
Close a file
f.close()
f.close('modified 2006/05/03')
Close the file, adding a line to the global 'history' attribute.Get the global attributes in the file
These constructs returns the global attributes names from the file:globalAtts = f.attributes.keys() globalAtts = f.__dict__.keys() # deprecated
The global attribute names are also returned by the Pythondir()
function, as in:globalAtts_plus = dir(f)
However, in this case, mixed in with the actual global attributes are the methods attached to the NioFile object. If you are only interested in the file attributes, you would need to cull out the method attributes:'close'
,'create_dimension'
, and'create_variable'
.You can get all the global attributes along with their associated values by getting the whole attribute dictionary. The following lines of code are equivalent:
globalAttsAndVals = f.attributes globalAttsAndVals = getattr(f,'attributes') globalAttsAndVals = f.__dict__ # deprecated globalAttsAndVals = getattr(f,'__dict__') # deprecated
Get the value of a global attribute by name
The following lines are equivalent:globalAttVal = f.globalAttNam globalAttVal = f.attributes['globalAttName'] globalAttVal = f.__dict__['globalAttName'] # deprecated globalAttVal = getattr(f,'globalAttName')
Note that all numerical attribute values are returned as NumPy arrays, including scalar values. Character array attributes are returned as Python strings.Check for the existence of a global attribute
if hasattr(f,'globalAttName'): do_whatever
Get the dimension names from the file
dimNames = f.dimensions.keys()
Get the size of a dimension by name
dimSize = f.dimensions['dimName']
Get the sizes of all dimensions in the same order as the names
dim_sizes = f.dimensions.values()
Get all the variable names in the file
varNames = f.variables.keys()
Print a summary of a variable in the file
print f.variables['varName']
Here is a sample print of the variable "elev":Variable: elev Type: float Total Size: 259200 bytes 64800 values Number of Dimensions: 2 Dimensions and sizes: [lat | 180] x [lon | 360] Coordinates: lat: [89.5..-89.5] lon: [0.5..359.5] Number of Attributes: 3 units : meters long_name : median topography _FillValue : -99999
Get a variable object reference to a specific variable in the file
var = f.variables['varName']
Get the type, number of dimensions, dimension sizes, and dimension names of a variable object
Assumingvar = f.variables['varName']
thentype = var.typecode() numDims = var.rank dimSizes = var.shape dimNames = var.dimensions
Note thattypecode()
is a function, whilerank
,shape
anddimensions
are attributes of the NioVariable object type.If the variable is scalar, the
rank
attribute is set to 0, while theshape
anddimensions
attributes are both empty tuples.The typecode method generally returns a 1 or 2 character string with the same significance as the for the type argument in the NioFile create_variable method. Note however that in the current release the typecode returned for variable created as type 'long' is always
'i'
. Also note that GRIB files that have an ensemble dimension contain an ensemble_info variable that is an array of strings. In this case, the NumPy version of PyNIO returns the type as 'Sn' where n represents the length of the strings.Get the attributes of a variable
Assumingvar = f.variables['varName']
varAtts = var.attributes.keys() varAtts = var.__dict__.keys() # deprecated
As with global attributes, you can also get the variable attributes using thedir()
function. However, the methods of the NioVariable object are also included in the return value. These are'assign_value'
,'get_value'
, and'typecode'
.varAtts_plus = dir(var)
You can get all the variable attributes and their associated values by getting the whole attribute dictionary. The following lines of code are equivalent:
varAttsAndVals = var.attributes varAttsAndVals = getattr(var,'attributes') varAttsAndVals = var.__dict__ # deprecated varAttsAndVals = getattr(var,'__dict__') # deprecated
Get the value of a variable attribute
Assumingvar = f.variables.['varName']
The following 4 lines are equivalent:varAttVal = var.varAttName varAttVal = var.attributes['varAttName'] varAttVal = var.__dict__['varAttName'] # deprecated varAttVal = getattr(var,'varAttName')
Note that all numerical attribute values are returned as NumPy arrays, including scalar values. Character array attributes are returned as Python strings.Check for the existence of a variable attribute
if hasattr(f.variables['varName'],'varAttName'): do_whatever
Get the data in a variable object into a NumPy array
If the variable is not scalar (rank > 0):
data = f.variables.['varName'][:]
ordata = f.variables.['varName'],get_value()
Assuming the shape of the variable is (5,20,30) get a slice along the first element of the first dimension:var = f.variables.['varName'] data = var[0]
Get the same slice but reverse the elements of the second dimension. The following two statements are equivalent:data = var[0,::-1,:] data = var[0,19::-1,:]
Note that when using a negative stride in Python the first subscript must be larger than the second. Also since the second subscript is an excluded bound, logically you would need a -1 for the second index if you wanted to explicitly specify all indexes including 0 (for this example, var[0,19:-1:-1,:] to reverse the entire second dimension). However, because negative subscripts in Python wrap around from the highest array index, a '-1' as the second subscript is equivalent to the '19', and the subscript 19:-1:-1 selects only one element of the 20 element array dimension.If the variable is scalar (rank == 0):
Scalar NioVariable objects cannot be subscripted. Therefore the only way to retrieve the variable value is to use theget_value
method:scalar_data = var.get_value()
Note thatscalar_value
is still a NumPy array. It can be distinguished as a scalar value because its shape attribute is an empty tuple:scalar_data.shape == ()
evaluates toTrue
.Subset selection using associated coordinate variable values:
You can specify subsets using the values of associated coordinate variables. For information about this feature see PyNIO Extended Selection.Get all the group names in the file
(1.5.0 or later)f = Nio.open_file(filename) print f.groups.keys()
Open a particular group in the file
(1.5.0 or later)g = f.groups['/U_MARF/MSG/Level1_5/DATA/Channel_07'] print g print type(g) # NioFile
'g' is now a NioFile which you can then used the previously discussed methods for reading data and metadta.g = f.groups['/U_MARF/MSG/Level1_5/DATA/Channel_07'] print g.variables.keys() img_data = g.variables['IMAGE_DATA'][:]
The following operations require the file to be opened for writing.
Create a global attribute in the file
The following 2 statements are equivalentf.globalAttName = globalAttVal setattr(f,'globalAttName',globalAttVal)
Note that creating an attribute by creating a new element in theattributes
(or__dict__
) dictionary does not work even though no error is raised and the attribute subsequently appears to be present in the dictionary.Create a dimension in the file
Assuming 'dimName' is a string, rather than a variable, create a dimension of length 74:f.create_dimension('dimName',74)
Create a variable in the file
Create a variable named 'varName', of type float, and two dimensions named 'dim1' and 'dim2'. The dimensions must already exist. A NioVariable object is returned.var = f.create_variable('varName','f',('dim1',dim2'))
Types corresponding to the single character type designators that can be used to create file variables are as follows:
- 'd': 64 bit float
- 'f': 32 bit float
- 'l': long
- 'i': 32 bit integer
- 'h': 16 bit integer
- 'b': 8 bit integer
- 'S1': character
The long ('l') type is 32 bits (the same as an integer 'i' type) on 32-bit computing platforms, but it is 64 bits in versions of PyNIO created for 64-bit computers. However, because NetCDF and HDF 4, the writable file formats, do not support 64-bit integers, PyNIO converts 64-bit integers to 32-bit integers before writing data to the file. PyNIO issues a warning about possible data loss, but does not check individual elements to see if any exceed the maximum value of a 32-bit integer.The dimensions parameter is a tuple. If you are creating a single dimensional variable, and, therefore, the tuple has only one element, you must place a comma after the dimension name for Python to recognize it properly, e.g:
('dim1',)
. To create a scalar variable use an empty tuple:( )
.Create an attribute of a variable in the file
The following 2 statements are equivalentf.variables['varName'].varAttName = varAttVal setattr(f.variables['varName'],'varAttName',varAttVal)
As with global attributes, attempting to create an attribute by modifying the variable'sattributes
(or__dict__
) dictionary does not work even though no error is raised and the attribute subsequently appears to be present in the dictionary.Assigning values to a variable in the file
If the variable is not scalar (rank > 0):
You assign values to a file variable either using the subscript syntax or using theassign_value
method. Assumingdata
is a NumPy array or a Python sequence containing the same number of elements as the target file variable, the following statements are equivalent:f.variables['varName'][:] = data f.variables['varName'].assign_value(data)
Also note that, even though it may look somewhat counterintuitive, assigning to a NioVariable object variable also works:var = f.variables['varName'] # create a NioVariable object variable var[:] = data # or var.assign_value(data)
Using other subscripting syntax, you can assign to subsets of the file variable. For instance, supposevar.shape
is equal to (5,6). Then you could make assignments like the following:var[1] = ( 1,2,3,4,5,6 ) # assign values to all elements indexed by the second element of the first dimension var[1:3,2:4] = ((12,13),(22,23)) # assign values to a 2x2 rectangular sub-space of the variable
You can assign values to character variables using Python strings. The last dimension of the variable should have a size equal to the length of the string. Strings used to populate multidimensional character variables should all have the same length. Pad shorter strings with blanks at the end.If the variable is scalar (rank == 0):
Scalar NioVariable objects cannot be subscripted. Therefore the only way to assign a value to a scalar variable is to use theassign_value
method:f.variables['scalar_var'].assign_value(42.0)
Subset selection using associated coordinate variable values:
You can specify subsets using the values of associated coordinate variables. For information about this feature see PyNIO Extended Selection.
Note: the preceding usage information was modeled after this guide to the Python NetCDF module