getitem#

named_arrays.getitem(a, item)#

Recursively index an arbitrarily-nested structure with a named index.

The index item is applied only to the leaves of a that are compatible with the named_arrays API (see named_array_like()). Containers (dict, list, tuple) and dataclasses are traversed recursively, and any other leaf value is returned unchanged.

Parameters:
  • a (Any) – The structure to index. May be a named array, a (possibly nested) dict, list, or tuple of named arrays, a dataclasses instance whose fields are named arrays, or any other value (which is returned unchanged).

  • item (dict | AbstractArray) – The named index to apply to each array-like leaf of a, for example a dict mapping axis names to index arrays.

Returns:

  • A structure with the same shape as a where every array-like leaf

  • has been indexed by item.

Return type:

Any

Examples

import numpy as np
import named_arrays as na

a = na.arange(0, 5, axis="x")
index = {"x": na.ScalarArray(np.array([1, 3]), axes="x")}

na.getitem({"foo": a, "bar": 2 * a}, index)
{'foo': ScalarArray(
     ndarray=[1, 3],
     axes=('x',),
 ),
 'bar': ScalarArray(
     ndarray=[2, 6],
     axes=('x',),
 )}

Notes

A tuple leaf is rebuilt as a plain tuple, so the subtype of a typing.NamedTuple is not preserved.