Skip to main content
`Ctrl`+`K`

# pandas.api.extensions.register_index_accessor

pandas.api.extensions.register_index_accessor(name)

  Register a custom accessor on Index objects.

  Parameters:
    name str

      Name under which the accessor should be registered. A warning is issued if this name conflicts with a preexisting attribute.

  Returns:
    callable

      A class decorator.

  See also

  `register_dataframe_accessor`

    Register a custom accessor on DataFrame objects.

  `register_series_accessor`

    Register a custom accessor on Series objects.

  `register_index_accessor`

    Register a custom accessor on Index objects.

  Notes

  This function allows you to register a custom-defined accessor class for Index. The requirements for the accessor class are as follows:

  - Must contain an init method that:

    - accepts a single Index object

    - raises an AttributeError if the Index object does not have correctly matching inputs for the accessor

  - Must contain a method for each access pattern.

    - The methods should be able to take any argument signature.

    - Accessible using the @property decorator if no additional arguments are needed.

  Examples

  An accessor that only accepts integers could have a class defined like this:

      >>> @pd.api.extensions.register_index_accessor("int_accessor")
      ... class IntAccessor:
      ...     def __init__(self, pandas_obj):
      ...         if not all(isinstance(x, int) for x in pandas_obj):
      ...             raise AttributeError("The index must only be an integer value")
      ...         self._obj = pandas_obj
      ...
      ...     def even(self):
      ...         return [x for x in self._obj if x % 2 == 0]
      >>> df = pd.DataFrame.from_dict(
      ...     {"row1": {"1": 1, "2": "a"}, "row2": {"1": 2, "2": "b"}}, orient="index"
      ... )
      >>> df.index.int_accessor
      Traceback (most recent call last):
      ...
      AttributeError: The index must only be an integer value.
      >>> df = pd.DataFrame(
      ...     {"col1": [1, 2, 3, 4], "col2": ["a", "b", "c", "d"]}, index=[1, 2, 5, 8]
      ... )
      >>> df.index.int_accessor.even()
      [2, 8]