Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions doc/internals/how-to-create-custom-index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,46 @@ e.g., a kd-tree object may not be easily indexed. If ``Index.isel()`` is not
implemented, the index in just dropped in the DataArray or Dataset resulting
from the selection.

Custom representation
---------------------

When a :py:class:`Dataset` or :py:class:`DataArray` is displayed, Xarray shows
a summary of its indexes. By default, the base :py:class:`Index` class returns
just the class name. You can customize this by implementing the
:py:meth:`Index._repr_inline_` method, which should return a short, single-line
string representation of the index.

The ``_repr_inline_`` method receives a ``max_width`` argument (number of
characters) that indicates the available space for the representation. If the
representation exceeds this width, it should be truncated:

.. jupyter-execute::

from xarray import Index

class MyIndex(Index):
def __init__(self, data):
self._data = data

def _repr_inline_(self, max_width: int) -> str:
# Return a concise representation
return f"{self.__class__.__name__} (size={len(self._data)})"

Here are some examples from Xarray's built-in indexes:

- ``RangeIndex`` returns: ``RangeIndex (start=0, stop=1, step=0.1)``
- ``NDPointIndex`` returns: ``NDPointIndex (KDTree)``
Comment on lines +158 to +159
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If possible to link to the source code for these (ideally linked to the release) that would be amazing. but no worries if that's too difficult ot get working with auto updating permalinks.


This representation appears in the indexes section when displaying a Dataset or
DataArray:

.. code-block:: none

<xarray.DataArray (x: 10)>
...
Indexes:
x MyIndex (size=10)
Comment on lines +164 to +169
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be a jupyter-execute block? to make sure this stays up to date


Alignment
---------

Expand Down Expand Up @@ -198,6 +238,10 @@ regularly spaced 2-dimensional data) that internally relies on two

return merge_sel_results(results)

def _repr_inline_(self, max_width: int) -> str:
dims = [idx.dim for idx in self._xy_indexes.values()]
return f"{self.__class__.__name__} (dims={dims})"


This basic index only supports label-based selection. Providing a full-featured
index by implementing the other ``Index`` methods should be pretty
Expand Down
Loading