pandas.api.extensions.register_dataframe_accessor #
- pandas.api.扩展。register_dataframe_accessor ( name ) [来源] #
在 DataFrame 对象上注册自定义访问器。
- 参数:
- 名称字符串
访问者应注册的名称。如果该名称与预先存在的属性冲突,则会发出警告。
- 返回:
- 可调用的
一个类装饰器。
也可以看看
register_dataframe_accessor
在 DataFrame 对象上注册自定义访问器。
register_series_accessor
在 Series 对象上注册自定义访问器。
register_index_accessor
在 Index 对象上注册自定义访问器。
笔记
访问时,您的访问器将使用用户正在交互的 pandas 对象进行初始化。所以签名必须是
def __init__(self, pandas_object): # noqa: E999 ...
AttributeError
为了与 pandas 方法保持一致,如果传递给访问器的数据的数据类型不正确,则应引发 an错误。>>> 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