cf.Variable

class cf.Variable(attributes={})

Bases: object

Base class for storing a data array with metadata.

A variable contains a data array and metadata comprising properties to describe the physical nature of the data.

All components of a variable are optional.

Initialization

Parameters :
attributes : dict, optional

Initialize a new instance with attributes from the dictionary’s key/value pairs. Values are deep copied.

binary_mask()

return new variable containing binary mask

chunk(chunksize=None, extra_boundaries=[], adim=[])

Partition the data array using Large Amounts of Massive Arrays (LAMA) functionality.

Parameters :

chunksize : int

extra_boundaries : list

adim : list

Returns :

extra_boundaries, adim : {list, list}

copy(_omit_special=())

Return a deep copy.

Equivalent to copy.deepcopy(f).

Returns :
out :

The deep copy.

Examples

>>> g = f.copy()
delattr(attr)

Delete a standard or non-standard CF attribute.

Parameters :
attr : str

The name of the attribute to delete.

Returns :

None

Raises :
AttributeError :

If the variable does not have the named attribute.

Examples

>>> f.delattr('standard_name')
>>> f.delattr('foo')
dump(id=None, omit=())

Return a string containing a full description of the instance.

Parameters :
id : str, optional

Set the common prefix of component names. By default the instance’s class name is used.

omit : sequence of strs

Omit the given attributes from the description.

Returns :
out : str

A string containing the description.

Examples

>>> x = v.dump()
>>> print v.dump()
>>> print v.dump(id='variable1')
>>> print v.dump(omit=('long_name',))
equals(other, rtol=None, atol=None, traceback=False, ignore=set([]))

True if two variables are logically equal, False otherwise.

Parameters :
other :

The object to compare for equality.

atol : float, optional

The absolute tolerance for all numerical comparisons, By default the value returned by the ATOL function is used.

rtol : float, optional

The relative tolerance for all numerical comparisons, By default the value returned by the RTOL function is used.

traceback : bool, optional

If True then print a traceback highlighting where the two instances differ.

ignore : set, optional

Omit these attributes from the comparison.

Returns :
out : bool

Whether or not the two instances are equal.

Examples

>>> f.equals(f)
True
>>> g = f + 1
>>> f.equals(g)
False
>>> g -= 1
>>> f.equals(g)
True
>>> f.setattr('name', 'name0')
>>> g.setattr('name', 'name1')
>>> f.equals(g)
False
expand_dims(axis, dim, direction)

axis is an integer dim is a string direction is a boolean

extract(*args, **kwargs)

Return the instance if it matches the given conditions.

Equivalent to:

def extract(f, *args, **kwargs):
    if f.match(*args, **kwargs):
        return f
    raise ValueError('')
Parameters :
args, kwargs :

As for the match method.

Returns :
out :

The variable as an object identity, if it matches the given conditions.

Raises :
ValueError :

If the variable does not match the conditions.

getattr(attr, *default)

Get a standard or non-standard CF attribute.

Parameters :
attr : str

The name of the attribute to get.

default : optional

Return default if and only if the variable does not have the named attribute.

Returns :
out :

The value of the named attribute, or the default value.

Raises :
AttributeError :

If the variable does not have the named attribute a default value has not been set.

Examples

>>> f.getattr('standard_name')
>>> f.getattr('standard_name', None)
>>> f.getattr('foo')
hasattr(attr)

Return True if the variable has standard or non-standard CF attribute.

Parameters :
attr : str

The name of the attribute.

Returns :
out : bool

True if the instance has the attribute.

Examples

>>> f.hasattr('standard_name')
>>> f.hasattr('foo')
match(attr={}, priv={})

Determine whether or not a variable matches conditions on its attributes.

Parameters :
attr : dict

Dictionary for which each key/value pair is a standard or non-standard CF attribute name and a condition for the attribute to be tested against. If the value is a sequence of conditions then the attribute matches if at least one of the conditions is passed.

In general, a condition is any object and it is passed if the attribute is equal to the object, with the following exceptions:

  • If the attribute is string-valued, then the condition may be a regular expression pattern recognised by the re module and the condition is passed if the attribute matches the regular expression. Special characters for the start and end of the string are assumed and need not be included. For example, ‘.*wind’ is equivalent to ‘^.*wind$’.
  • For the ‘Units’ attribute, the condition is passed if the attribute is equivalent (rather than equal) to the object. (Note that this behaviour does not apply to the ‘units’ attribute.)
priv : dict, optional

Dictionary for which each key/value pair is an attribute name other than their standard and non-standard CF attribute and a condition for the attribute to be tested against. If the value is a sequence of conditions then the attribute matches if at least one of the conditions is passed.

In general, a condition behaves as for attr, with the following exception:

  • For the Units attribute, the condition is passed if the attribute is equivalent (rather than equal) to the object. (Note that this behaviour does not apply to the units attribute.)
Returns :
out : bool

Whether or not the variable matches the given criteria.

Examples

name(long_name=False, ncvar=False, default=None)

Return a name for the variable.

Returns the standard_name, long_name (if requested) or netCDF variable name (if requested), whichever it finds first, otherwise returns a default name.

Parameters :

long_name : bool, optional

If True, return the long_name if standard_name does not exist.

ncvar : bool, optional

If True, return ncvar if neither the standard_name nor long_name has already been returned.

default : str, optional

Return default if neither standard_name, long_name nor ncvar has already been returned.

Returns :
name : str

The name of the variable.

override_units(new_units)

Override the data array units in place.

Not to be confused with setting the Units attribute to units which are equivalent to the original units.

This is different to setting the Units attribute, as the new units need not be equivalent to the original ones and the data array elements will not be changed to reflect the new units.

Parameters :
new_units : str or Units

The new units for the data array.

Returns :

None

Examples

>>> f.Units
<CF Units: hPa>
>>> f.first_datum
100000.0
>>> f.override_units('km')
>>> f.Units
<CF Units: km>
>>> f.first_datum
100000.0
>>> f.override_units(cf.Units('watts'))
>>> f.Units
<CF Units: watts>
>>> f.first_datum
100000.0
reverse_dims(axes=None)

Reverse the directions of the data array dimensions in place.

Equivalent to indexing the specified dimensions with ::-1.

Parameters :
axes : int or sequence of ints

By default all dimensions are reversed.

Returns :
out : list of ints

The axes which were reversed, in arbitrary order.

Examples

>>> f.reverse_dims()
>>> f.reverse_dims(1)
>>> f.reverse_dims([0, 1])
setattr(attr, value)

Set a standard or non-standard CF attribute.

Parameters :
attr : str

The name of the attribute to set.

value :

The value for the attribute.

Returns :

None

Examples

>>> f.setattr('standard_name', 'time')
>>> f.setattr('foo', 12.5)
squeeze(axes=None)

axes are integers

transpose(axes=None)

axes are integers

Data

The Data object containing the data array.

Examples

>>> f.Data
<CF Data: >
Units

The Units object containing the units of the data array.

Stores the units and calendar CF attributes in an internally consistent manner. These attributes are mirrored by the units and calendar attributes respectively.

Examples

>>> f.Units
<CF Units: K>
add_offset

The add_offset CF attribute.

This attribute is only used when writing to a file on disk.

Examples

>>> f.add_offset = -4.0
>>> f.add_offset
-4.0
>>> del f.add_offset
array

A numpy array deep copy of the data array.

Changing the returned numpy array does not change the data array.

Examples

>>> a = f.array
>>> type(a)
<type 'numpy.ndarray'>
>>> a
array([0, 1, 2, 3, 4])
>>> a[0] = 999
>>> f.array
array([0, 1, 2, 3, 4])
attributes

A dictionary of the standard and non-standard CF attributes.

Note that modifying the returned dictionary will not change the attributes.

Examples

>>> f.attributes
{'Conventions': 'CF-1.0',
 '_FillValue': 1e+20,
 'cell_methods': <CF CellMethods: time: mean>,
 'experiment_id': 'stabilization experiment (SRES A1B)',
 'long_name': 'Surface Air Temperature',
 'standard_name': 'AIR_TEMP',
 'title': 'SRES A1B',
 'units': 'K'}
calendar

The calendar CF attribute.

This attribute is a mirror of the calendar stored in the Units attribute.

Examples

>>> f.calendar = 'noleap'
>>> f.calendar
'noleap'
>>> del f.calendar
comment

The comment CF attribute.

Examples

>>> f.comment = 'a comment'
>>> f.comment
'a comment'
>>> del f.comment
dtype

Numpy data-type of the data array.

Examples

>>> f.dtype
dtype('float64')
first_datum

The first element of the data array.

Equivalent to f.subset[(0,)*f.ndim].array.item()

Examples

>>> f.array
array([[1, 2],
       [3, 4]])
>>> f.first_datum
1
history

The history CF attribute.

Examples

>>> f.history = 'created on 2012/10/01'
>>> f.history
'created on 2012/10/01'
>>> del f.history
is_scalar

True if and only if the data array is a scalar array.

Examples

>>> f.array
array(2)
>>> f.is_scalar
True
>>> f.array
array([2])
>>> f.is_scalar
False
last_datum

The last element of the data array.

Equivalent to f.subset[(-1,)*f.ndim].array.item()

Examples

>>> f.array
array([[1, 2],
       [3, 4]])
>>> f.first_datum
4
leap_month

The leap_month CF attribute.

Examples

>>> f.leap_month = 2
>>> f.leap_month
2
>>> del f.leap_month
leap_year

The leap_year CF attribute.

Examples

>>> f.leap_year = 1984
>>> f.leap_year
1984
>>> del f.leap_year
long_name

The long_name CF attribute.

Examples

>>> f.long_name = 'zonal_wind'
>>> f.long_name
'zonal_wind'
>>> del f.long_name
mask

The boolean missing data mask of the data array.

Returned as a Data object. The mask may be set to ‘no missing data’ by deleting the attribute.

Examples

>>> f.shape
(12, 73, 96)
>>> m = f.mask
>>> type(m)
<cf.data.Data>
>>> m.dtype
dtype('bool')
>>> m.shape
[12, 73, 96]
>>> m.array.shape
(12, 73, 96)
>>> del f.mask
>>> f.array.mask
False
>>> import numpy
>>> f.array.mask is numpy.ma.nomask
True
missing_value

The missing_value CF attribute.

This attribute is forced to be consistent with the _FillValue attribute as follows:

  • Assigning a value to the missing_value attribute also assigns the same value to the _FillValue attribute whether the latter has been previously set or not.
  • Assigning a value to the _FillValue attribute also assigns the same value to the missing_value attribute, but only if the latter has previously been defined.

Examples

>>> f.missing_value = 1e30
>>> f.missing_value
1e30
>>> f._FillValue
1e30
>>> del f.missing_value
>>> f._FillValue
1e30
month_lengths

The month_lengths CF attribute.

ndim

Number of dimensions in the data array.

Examples

>>> f.shape
(73, 96)
>>> f.ndim
2
scale_factor

The scale_factor CF attribute.

This attribute is only used when writing to a file on disk.

Examples

>>> f.scale_factor = 10.0
>>> f.scale_factor
10.0
>>> del f.scale_factor
shape

Tuple of the data array’s dimension sizes.

Examples

>>> f.shape
(73, 96)
size

Number of elements in the data array.

Examples

>>> f.shape
(73, 96)
>>> f.size
7008
standard_name

The standard_name CF attribute.

Examples

>>> f.standard_name = 'time'
>>> f.standard_name
'time'
>>> del f.standard_name
subset

Return a new variable whose data is subsetted.

This attribute may be indexed to select a subset from dimension index values.

Subsetting by indexing

Subsetting by dimension indices uses an extended Python slicing syntax, which is similar numpy array indexing. There are two extensions to the numpy indexing functionality:

  • Size 1 dimensions are never removed.

    An integer index i takes the i-th element but does not reduce the rank of the output array by one.

  • When advanced indexing is used on more than one dimension, the advanced indices work independently.

    When more than one dimension’s slice is a 1-d boolean array or 1-d sequence of integers, then these indices work independently along each dimension (similar to the way vector subscripts work in Fortran), rather than by their elements.

Examples

units

The units CF attribute.

This attribute is a mirror of the units stored in the Units attribute.

Examples

>>> f.units = 'K'
>>> f.units
'K'
>>> del f.units
valid_max

The valid_max CF attribute.

Examples

>>> f.valid_max = 100.0
>>> f.valid_max
100.0
>>> del f.valid_max
valid_min

The valid_min CF attribute.

Examples

>>> f.valid_min = 100.0
>>> f.valid_min
100.0
>>> del f.valid_min
valid_range

The valid_range CF attribute.

May be set as a numpy array, a list or a tuple. Always returned as a tuple.

Examples

>>> f.valid_range = array([100., 400.])
>>> f.valid_range
(100.0, 400.0)
>>> del f.valid_range
>>> f.valid_range = (50., 450.)
varray

A numpy array view of the data array.

Changing the elements of the returned view changes the data array.

Examples

>>> a = f.varray
>>> type(a)
<type 'numpy.ndarray'>
>>> a
array([0, 1, 2, 3, 4])
>>> a[0] = 999
>>> f.varray
array([999, 1, 2, 3, 4])

Previous topic

cf.CfList

Next topic

cf.VariableList

This Page