如何访问自定义数据框访问器的命名空间?

huangapple go评论60阅读模式
英文:

How to access custom dataframe accessor's namespace?

问题

根据Pandas 文档,可以像下面这样注册自定义访问器:

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

    @property
    def center(self):
        lat = self._obj.latitude
        lon = self._obj.longitude
        return (float(lon.mean()), float(lat.mean()))

    def method(self):
        # 做一些操作

假设有更多带有不同命名空间的访问器,例如:

  • geo2
  • geo3

如果我们想从 geo 中调用一个方法,可以这样做:

df.geo.method() # 这里我们明确使用了 geo

如何将一个命名空间存储/检索到一个变量中呢?

我考虑的方法大致是:

df.variable_namespace.method() # variable_namespace 可以是 geo、geo2 等等...

如果我们想要在命名空间方面具有动态行为呢?

英文:

According to Pandas docs it is possible to register custom accessors like below:

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

    @property
    def center(self):
        lat = self._obj.latitude
        lon = self._obj.longitude
        return (float(lon.mean()), float(lat.mean()))

    def method(self):
        # do something

Suppose that there are more accessors with different namespaces. For instance:

  • geo2
  • geo3

If we'd like to invoke a method from geo, for example, we'd do:

df.geo.method() # here we use geo explicitly

How could I store/retrieve a namespace to/from a variable?

I am thinking something along the lines of:

df.variable_namespace.method() # variable_namespace could be geo, geo2 etc..

What if we'd like to have dynamic behavior as far as namespaces are concerned?

答案1

得分: 0

让我们考虑一个变量负责存储一个命名空间,如下所示:

variable_namespace = 'geo' # 或 'geo2'、'geo3' 等等。

然后,可以实现动态行为:

df.__getattr__(variable_namespace).method()
英文:

Let's consider that a variable is responsible for storing a namespace as such:

variable_namespace = 'geo' # or 'geo2', 'geo3' etc.

Then, it is possible to achieve dynamic behavior:

df.__getattr__(variable_namespace).method()

huangapple
  • 本文由 发表于 2023年2月23日 20:26:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定