pandas.api.extensions.register_dataframe_accessor#

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

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

Parameters:
namestr

访问器应注册的名称。如果此名称与预先存在的属性冲突,则会发出警告。

Returns:
callable

类装饰器。

参见

register_dataframe_accessor

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

register_series_accessor

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

register_index_accessor

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

Notes

访问时,您的访问器将使用用户正在交互的 pandas 对象进行初始化。因此,签名必须是

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

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

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

Examples

在您的库代码中:

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