I am subclassing pandas DataFrame and I want to have an attribute.
class MyFrame(pd.DataFrame):
_metadata = ['myattr']
myattr = []
def __init__(self, *args, **kwargs):
pd.DataFrame.__init__(self, *args, **kwargs)
self.myattr.append(0)
@property
def _constructor(self):
return AutoData
My issue is that myattr is a class attribute. When I modify it in an instance of my class, every instances got modified:
mf2 = mf
mf2.myattr.append(1)
print(mf.myattr)
>>> [0, 1]
But I want the attribute to be attached with its instance. In other word, modify myattr only for mf2 but not for mf. Thank you.
__init__self.myattr = [], by this you are sure this is instance's attribute ;)myattrwill not be attached to copies of my object and (2) it gives this warning: UserWarning: Pandas doesn't allow columns to be created via a new attribute nameself.df = pd.DataFrame. Composition in this case looks like better solution because it will not need from you to adjust to DataFrame implementation at cost of wrapping it. Of course this isn't best solution at all cases but still, consider it :)__init__and redefining thecopymethod which now copy also my attribute to the new DataFrame. Then I usecopy()to duplicate my object.