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

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

How to access custom dataframe accessor's namespace?

问题

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

  1. @pd.api.extensions.register_dataframe_accessor("geo")
  2. class GeoAccessor:
  3. def __init__(self, pandas_obj):
  4. self._validate(pandas_obj)
  5. self._obj = pandas_obj
  6. @property
  7. def center(self):
  8. lat = self._obj.latitude
  9. lon = self._obj.longitude
  10. return (float(lon.mean()), float(lat.mean()))
  11. def method(self):
  12. # 做一些操作

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

  • geo2
  • geo3

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

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

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

我考虑的方法大致是:

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

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

英文:

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

  1. @pd.api.extensions.register_dataframe_accessor("geo")
  2. class GeoAccessor:
  3. def __init__(self, pandas_obj):
  4. self._validate(pandas_obj)
  5. self._obj = pandas_obj
  6. @property
  7. def center(self):
  8. lat = self._obj.latitude
  9. lon = self._obj.longitude
  10. return (float(lon.mean()), float(lat.mean()))
  11. def method(self):
  12. # 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:

  1. 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:

  1. 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

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

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

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

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

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

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

Then, it is possible to achieve dynamic behavior:

  1. 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:

确定