pandas.api.extensions.register_series_accessor#

pandas.api.extensions.register_series_accessor(name)[源代码]#

在Series对象上注册自定义访问器。

参数
name应力

应该用来注册访问者的名称。如果此名称与先前存在的属性冲突,则会发出警告。

退货
可调用

一名班级装饰师。

参见

register_dataframe_accessor

在DataFrame对象上注册自定义访问器。

register_series_accessor

在Series对象上注册自定义访问器。

register_index_accessor

在Index对象上注册自定义访问器。

注意事项

访问时,您的访问器将使用用户正在与之交互的Pandas对象进行初始化。所以签名一定是

def __init__(self, pandas_object):  # noqa: E999
    ...

为了与Pandas方法保持一致,您应该引发 AttributeError 如果传递给访问器的数据具有不正确的数据类型。

>>> pd.Series(['a', 'b']).dt
Traceback (most recent call last):
...
AttributeError: Can only use .dt accessor with datetimelike values

示例

在您的库代码中::

import pandas as pd

@pd.api.extensions.register_dataframe_accessor("geo")
class GeoAccessor:
    def __init__(self, pandas_obj):
        self._obj = pandas_obj

    @property
    def center(self):
        # return the geographic center point of this DataFrame
        lat = self._obj.latitude
        lon = self._obj.longitude
        return (float(lon.mean()), float(lat.mean()))

    def plot(self):
        # plot this array's data on a map, e.g., using Cartopy
        pass

返回交互式IPython会话:

In [1]: ds = pd.DataFrame({"longitude": np.linspace(0, 10),
   ...:                    "latitude": np.linspace(0, 20)})
In [2]: ds.geo.center
Out[2]: (5.0, 10.0)
In [3]: ds.geo.plot()  # plots data on a map