英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论