创建返回Pandas DataFrame的子类表单类
在我的项目中,我创建了一个类,核心是使用 pandas 的 DataFrame。这个数据框里的值是根据一些规范来的,我用一些字母来初始化它,表示我想处理的数据。我把所有用来创建数据框的函数放在 __init__
里,因为我觉得这些函数只需要运行一次,初始化后就不需要再用了。而且我也不想在后面的代码中访问这些函数。(我不确定这样做是否符合“Pythonic”的方式)。
在构建了基本的类,并实现了 __str__
和 plotData() 方法后,我想应用一些过滤器,并建立一个新类,其中额外的列就是这个过滤器。我想在 __init__
中做到这一点,但又想保留之前做的所有内容。换句话说,我不想重写整个 __init__
,只想在基本的数据框中添加新列。
以类似的方式,我还想在 plotData() 函数中添加一个额外的图表。
我的原始代码已经有不少行了,但原则上和下面列出的代码非常相似。
import pandas as pd
import pylab as pl
class myClass(object):
def __init__(self, frameType = 'All'):
def method1():
myFrame = pd.DataFrame({'c1':[1,2,3],'c2':[4,5,6],'c3':[7,8,9]})
return myFrame
def method2():
myFrame = pd.DataFrame({'c1':[.1,.2,.3],'c2':[.4,.5,.6],'c3':[.7,.8,.9]})
return myFrame
def makingChiose(self):
if self.frameType == 'All':
variable = method1() + method2()
elif self.frameType == 'a':
variable = method1()
elif self.frameType == 'b':
variable = method2()
else:
variable = pd.DataFrame({'c1':[0,0,0],'c2':[0,0,0],'c3':[0,0,0]})
#print 'FROM __init__ : %s' % variable
return variable
self.frameType = frameType
self.cObject = makingChiose(self) # object created by the class
def __str__(self):
return str(self.cObject)
def plotData(self):
self.fig1 = pl.plot(self.cObject['c1'],self.cObject['c2'])
self.fig2 = pl.plot(self.cObject['c1'],self.cObject['c3'])
pl.show()
class myClassAv(myClass):
def addingCol(self):
print 'CURRENT cObject \n%s' % self.cObject # the object is visible
self.cObject['avarage'] = (self.cObject['c1']+self.cObject['c2']+self.cObject['c3'])/3
print 'THIS WORKS IN GENERAL\n%s' % str((self.cObject['c1']+self.cObject['c2']+self.cObject['c3'])/3) # creating new column works
def plotData(self):
# Function to add new plot to already existing plots
self.fig3 = pl.plot(self.cObject['c1'],self.cObject['avarage'])
if __name__ == '__main__':
myObject1 = myClass()
print 'myObject1 =\n%s' % myObject1
myObject1.plotData()
myObject2 = myClass('a')
print 'myObject2 =\n%s' % myObject2
myObject3 = myClass('b')
print 'myObject3 =\n%s' % myObject3
myObject4 = myClass('c')
print 'myObject4 =\n%s' % myObject4
myObject5 = myClassAv('a').addingCol()
print 'myObject5 =\n%s' % myObject5
myObject5.plotData()
大部分代码在初始化时都能正常工作,但当我尝试创建一个带有额外列的新数据框时出现了错误。当我把新的 __init__
放进去时,我就创建了一个全新的初始化,这样就丢失了之前做的所有内容。我创建了一个新函数,但我更希望在调用新类时添加额外的列,而不是在新类内部调用一个函数。代码的输出看起来是这样的:
myObject1 =
c1 c2 c3
0 1.1 4.4 7.7
1 2.2 5.5 8.8
2 3.3 6.6 9.9
myObject2 =
c1 c2 c3
0 1 4 7
1 2 5 8
2 3 6 9
myObject3 =
c1 c2 c3
0 0.1 0.4 0.7
1 0.2 0.5 0.8
2 0.3 0.6 0.9
myObject4 =
c1 c2 c3
0 0 0 0
1 0 0 0
2 0 0 0
CURRENT cObject
c1 c2 c3
0 1 4 7
1 2 5 8
2 3 6 9
THIS WORKS IN GENERAL
0 4
1 5
2 6
myObject5 =
None
Traceback (most recent call last):
File "C:\Users\src\trys.py", line 57, in <module>
myObject5.plotData()
AttributeError: 'NoneType' object has no attribute 'plotData'
我的问题是:我能否“部分”覆盖父类的方法,以便在这个方法中保留之前的内容,并添加一些新功能?我希望将 myClassAv() 初始化为四列的数据框,而不是像 myClass() 那样的三列,并且希望 myClassAv().plotData() 能绘制第三条线,同时保留来自基类的两条线。
我不知道如何理解这个错误,以及为什么 myObject5 是 None,但我怀疑这和继承有关。
另外,如果你有建议,认为我应该用不同的方式来实现我的想法,我很乐意听取。
1 个回答
你可以在 myClassAv.__init__
里面直接调用 myClass.__init__
:
def __init__(self, frameType='All'):
myClass.__init__(self, frameType)
def addingCol(cObject):
...
addingCol(self.cObject)
为了更具体一点,
import pandas as pd
import pylab as pl
import numpy as np
class myClass(object):
def __init__(self, frameType='All'):
def method1():
myFrame = pd.DataFrame(
{'c1': [1, 2, 3], 'c2': [4, 5, 6], 'c3': [7, 8, 9]})
return myFrame
def method2():
myFrame = pd.DataFrame(
{'c1': [.1, .2, .3], 'c2': [.4, .5, .6], 'c3': [.7, .8, .9]})
return myFrame
def makingChoice(self):
if self.frameType == 'All':
variable = method1() + method2()
elif self.frameType == 'a':
variable = method1()
elif self.frameType == 'b':
variable = method2()
else:
variable = pd.DataFrame(
{'c1': [0, 0, 0], 'c2': [0, 0, 0], 'c3': [0, 0, 0]})
# print 'FROM __init__ : %s' % variable
return variable
self.frameType = frameType
self.cObject = makingChoice(self) # object created by the class
def __str__(self):
return str(self.cObject)
def plotData(self):
self.fig1 = pl.plot(self.cObject['c1'], self.cObject['c2'])
self.fig2 = pl.plot(self.cObject['c1'], self.cObject['c3'])
pl.show()
class myClassAv(myClass):
def __init__(self, frameType='All'):
myClass.__init__(self, frameType)
def addingCol(cObject):
print 'CURRENT cObject \n%s' % cObject # the object is visible
cObject['average'] = cObject.mean(axis=1)
# creating new column works
print 'THIS WORKS IN GENERAL\n%s' % str(cObject['average'])
return cObject
addingCol(self.cObject)
def plotData(self):
# Function to add new plot to already existing plots
self.fig3 = pl.plot(self.cObject['c1'], self.cObject['average'])
if __name__ == '__main__':
myObject1 = myClass()
print 'myObject1 =\n%s' % myObject1
myObject1.plotData()
myObject2 = myClass('a')
print 'myObject2 =\n%s' % myObject2
myObject3 = myClass('b')
print 'myObject3 =\n%s' % myObject3
myObject4 = myClass('c')
print 'myObject4 =\n%s' % myObject4
myObject5 = myClassAv('a')
print 'myObject5 =\n%s' % myObject5
myObject5.plotData()
顺便提一下,替代
self.cObject['avarage'] = (self.cObject['c1']+self.cObject['c2']+self.cObject['c3'])/3
你可以使用 mean(axis = 1)
:
self.cObject['average'] = self.cObject.mean(axis=1)