ndindex is a Python library designed for representing and manipulating objects that can serve as valid indices for NumPy arrays, including slices, integers, ellipses, None, and integer/boolean arrays, and tuples containing these types. It provides a uniform API for these objects, ensuring correct semantics aligned with NumPy's `ndarray` indexing rules. The current version is 1.10.1, and it maintains an active release cadence with recent updates.
pip install ndindexVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating `ndindex` objects from basic Python indices, canonicalizing slices (both generally and for a specific array shape), and converting an `ndindex` object back into a raw Python index suitable for use with NumPy arrays. It highlights the `reduce()` method for canonicalization and `raw` attribute for NumPy compatibility.
Always use `try-except IndexError` blocks when applying `idx.raw` to a NumPy array if out-of-bounds indexing is a possibility. Perform explicit bounds checking if needed before constructing the `ndindex` object if strict validation is required.
To canonicalize an index or reduce it to its simplest equivalent form, you must explicitly call the `.reduce()` method on the `ndindex` object (e.g., `Slice(None, 10).reduce()`). If comparing two indices for equivalence over a specific array shape, use `idx1.reduce(shape) == idx2.reduce(shape)` rather than `idx1 == idx2`. [1, 4]
To check if two `ndindex` objects are equivalent in terms of the elements they would select from an array, first call their `.reduce()` method, optionally with an array `shape` argument if the context is known. Then compare the reduced objects: `idx1.reduce(shape) == idx2.reduce(shape)`. [1]
Access the underlying NumPy-compatible index by using the `.raw` attribute of the `ndindex` object (e.g., `array[idx.raw]`).
To access the individual index objects within an `ndindex.Tuple`, use the `.args` attribute (which returns the `ndindex` types) or `.raw` (which returns the raw Python types for indexing, e.g., `idx.raw[0]`).
To find the indices of specific values in a NumPy array, use `numpy.where()` (e.g., `np.where(array == value)`).
Explicitly convert the floating-point number to an integer using `int()` before using it as an index or in functions that require integer arguments (e.g., `array[int(float_index)]`).