python - Method chaining for derived DataFrame class -



python - Method chaining for derived DataFrame class -

i trying extend pandas dataframe next code

class customframe(dataframe): def __init__(self): dataframe.__init__(self,{"a":[1,2,3,4],"b":[5,6,7,8]}) def get(self): homecoming self.loc[1] def foo(self): homecoming 2*self

now wanted chain method calls like:

>>> c=customframe() >>> c.get().foo() 'series' object has no attribute 'foo'

obviously .loc returns series doesn't know custom foo method. there way create work?

edit:

ideally like

c.method_from_data_frame().method_from_custom_frame().another_method_from_data_frame()

following advice of hyry i've overridden constructor of dataframe, need set properties on initialisation of customframe

class customframe(dataframe): def __init__(self, *args, **kw): super(customframe, self).__init__(*args, **kw) self.c = kw.get('c',false) @property def _constructor(self): homecoming customframe >>> c=customframe(c=5) >>> print c.c 5 >>> print c.get().c false

i tried utilize functools partial

@property def _constructor(self): homecoming partial(customframe,c=5)

but pandas.core.common.pandaserror: dataframe constructor not called! error. way alter get to

def get(self): ret = self.loc[[1]] # customframe default .c ret.c = self.c homecoming ret

which seems not elegant

you can override _constructor property, here example, because self.loc[1] returns series object, changed self.loc[[1]]:

from pandas import dataframe class customframe(dataframe): def __init__(self, *args, **kw): super(customframe, self).__init__(*args, **kw) @property def _constructor(self): homecoming customframe def get(self): homecoming self.loc[[1]] def foo(self): homecoming 2*self c=customframe({"a":[1,2,3,4],"b":[5,6,7,8]}) print c.get().foo()

edit

i have not improve thought re-create attributes, maybe can utilize _metadata or decorator, here illustration decorator:

def copy_attrs(func): def wrap_func(self, *args, **kw): res = func(self, *args, **kw) res.c = self.c homecoming res homecoming wrap_func class customframe(dataframe): def __init__(self, *args, **kw): self.__dict__["c"] = kw.pop("c", none) super(customframe, self).__init__(*args, **kw) @property def _constructor(self): homecoming customframe @copy_attrs def get(self): homecoming self.loc[:2] df = customframe({"a":[1,2,3,4],"b":[5,6,7,8]}, c=100) print df.c, df.get().c

python numpy pandas

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -