PyTables User's Guide: Hierarchical datasets in Python - Release 1.3.3
Prev | Appendix B. Using nested record arrays | Next

# B.2. NestedRecArray methods

To access the fields in the nested record array use the `field()` method:

    >>> print nra2.field('id')
    [1, 2]
    >>>

The `field()` method accepts also names of sub-fields. It will consist of several field name components separated by the string `'/'`, for instance:

    >>> print nra2.field('info/name')
    ['a1', 'a2']
    >>>

Eventually, the top level fields of the nested recarray can be accessed passing an integer argument to the `field()` method:

    >>> print nra2.field(1)
    [[ 0.5 1. ] [ 0.  0. ]]
    >>>

An alternative to the `field()` method is the use of the `fields` attribute. It is intended mainly for interactive usage in the Python console. For example:

    >>> nra2.fields.id
    [1, 2]
    >>> nra2.fields.info.fields.name
    ['a1', 'a2']
    >>>

Rows of nested recarrays can be read using the typical index syntax. The rows are retrieved as `NestedRecord` objects:

    >>> print nra2[0]
    (1L, array([ 0.5,  1. ], type=Float32), ('a1', 1j))
    >>>
    >>> nra2[0].__class__
    <class tables.nestedrecords.NestedRecord at 0x413cbb9c>

Slicing is also supported in the usual way:

    >>> print nra2[0:2]
    NestedRecArray[
    (1L, array([ 0.5,  1. ], type=Float32), ('a1', 1j)),
    (2L, array([ 0.,  0.], type=Float32), ('a2', (1+0.10000000000000001j)))
    ]
    >>>

Another useful method is `asRecArray()`. It converts a nested array to a non-nested equivalent array.

This method creates a new vanilla `RecArray` instance equivalent to this one by flattening its fields. Only bottom-level fields included in the array. Sub-fields are named by pre-pending the names of their parent fields up to the top-level fields, using `'/'` as a separator. The data area of the array is copied into the new one. For example, calling `nra3.asRecArray()` would return the same array as calling:

    >>> ra = numarray.records.array(
    ...     [(1, (0.5, 1.0), 'a1', 1j), (2, (0, 0), 'a2', 1+.1j)],
    ...     names=['id', 'pos', 'info/name', 'info/value'],
    ...     formats=['Int64', '(2,)Float32', 'a2', 'Complex64'])

Note that the shape of multidimensional fields is kept.

Prev | Home | Next
Using nested record arrays | Up | NestedRecord objects