如何防止 pandas 访问者发出覆盖警告?

How to prevent pandas accessor to issue override warning?

我已经编写了 pandas 数据帧的访问器,与 https://pandas.pydata.org/docs/reference/api/pandas.api.extensions.register_dataframe_accessor.html 中的示例非常相似。

@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()))

if __name__ == "__main__":
    ds = pd.DataFrame({"longitude": np.linspace(0, 10),
                   "latitude": np.linspace(0, 20)})
    print(ds.geo.center)

但是,当我第二次调用代码时,我收到警告信息

untitled3.py:12: UserWarning: registration of accessor <class '__main__.GeoAccessor'> under name 'geo' for type <class 'pandas.core.frame.DataFrame'> is overriding a preexisting attribute with the same name.
  class GeoAccessor:

我尝试在顶部添加以下行:

import warnings

warnings.filterwarnings(
    "ignore", message="registration of accessor <class '__main__.GeoAccessor'>")

但这只有在所有内容都在一个文件中时才有效。只要将文件存储在“testlib.py”中并在其他地方执行“导入测试库”,我就会再次收到相同的警告。

有什么想法吗?

在创建 try/except 块之前删除访问器。它可能不是很干净,但对我有用:

try:
    #delete the accessor to avoid warning 
    del pd.DataFrame.geo
except AttributeError:
    pass

@pd.api.extensions.register_dataframe_accessor("geo")
class GeoAccessor:
    ...

我尝试对 xarray 执行相同的操作,但它不起作用,因为 xarray 访问器是只读的。我收到此错误:

AttributeError: 'DataArray' object attribute 'myaccessor' is read-only