dtoolkit.accessor.register_index_method#

dtoolkit.accessor.register_index_method(name: str = None)[source]#

Index register accessor for human.

Write method normally, use method naturally.

Read more in the User Guide.

Parameters:
namestr, optional

Use the method name as the default accessor entrance if name is None.

Examples

In your library code:

from __future__ import annotations

from dtoolkit.accessor import register_dataframe_method
from dtoolkit.accessor import register_series_method
from dtoolkit.accessor import register_index_method
import pandas as pd

@register_index_method("col")  # Support alias name also.
@register_series_method("col")
@register_dataframe_method("col")
@register_index_method  # Use accessor method's `__name__` as the entrance.
@register_series_method
@register_dataframe_method
def cols(pd_obj) -> int | str | list[int | str] | None:
    '''
    An API to gather :attr:`~pandas.Series.name` and
    :attr:`~pandas.DataFrame.columns` to one.
    '''

    if isinstance(pd_obj, (pd.Series, pd.Index)):
        return pd_obj.name

    return pd_obj.columns.tolist()

Back in an interactive IPython session:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(
   ...:     {
   ...:         "a": [1, 2],
   ...:         "b": [3, 4],
   ...:     },
   ...:     index=pd.Index(
   ...:         ["x", "y"],
   ...:         name="c",
   ...:     ),
   ...: )

In [3]: df
Out[3]:
   a  b
c
x  1  3
y  2  4

Get the columns of DataFrame via `cols` or `col` method

In [4]: df.col()
Out[4]: ['a', 'b']

Get name of Series via `cols` or `col` method

In [5]: df.a.col()
Out[5]: 'a'

Get name of Index via `cols` or `col` method

In [6]: df.index.col()
Out[6]: 'c'