【发布时间】:2020-01-25 13:59:00
【问题描述】:
您好,我想对 pandas 数据框进行子类化,但数据框的子类也将继承自我自己的自定义类。我想这样做是因为我想创建多个子类数据框,以及其他将共享此基类的属性和方法的子类(不是数据框)。
开始我的基类是
class thing(object):
def __init__(self, item_location, name):
self.name = name
self.file = item_location
self.directory = os.path.join(*item_location.split(os.path.sep)[0:-1])
@property
def name(self):
return self._name
@name.setter
def name(self,val):
self._name = val
@property
def file(self):
return self._file
@file.setter
def file(self,val):
self._location = val
@property
def directory(self):
return self._directory
@directory.setter
def directory(self,val):
self._directory = val
现在我的子类之一将从熊猫和事物继承
class custom_dataframe(thing,pd.DataFrame):
def __init__(self, *args, **kwargs):
super(custom_dataframe,self).__init__(*args,**kwargs)
@property
def _constructor(self):
return custom_dataframe
我只是尝试制作一个空白数据框,并且只给它命名文件位置
custom_dataframe('/foobar/foobar/foobar.html','name')
我得到一个错误
(我无法在未连接到互联网的计算机上发布整个堆栈跟踪)
File "<stdin>", line 1, in <module>
File "<path to file with classes>", line x, in __init__
self.name = name
<a bunch of stuff going through pandas library>
File "<path to pandas generic.py>", line 4372, in __getattr__
return object.__getattribute__(self,name)
RecursionError: maximum recursion depth exceeded while calling a Python object
我正在使用熊猫 0.23.4
编辑:
将item_location.split(os.pathsep)[0:-1] 更改为*item_location.split(os.path.sep)[0:-1]
【问题讨论】:
-
我已经读过,正如我所说,我不想将我的事物属性添加为 _metadata,因为除了我的数据框子类之外的其他子类也将具有相同的属性。我宁愿不必在多个地方更改内容。
-
not have to change stuff in multiple places- 组合应该可以工作 - 在简单的情况下它可能看起来过于庞大,但效果会随着复杂性的增加而降低。无论如何,在您的情况下,尽量避免使用简单的属性名称,如name、file等。