Subclassing class returning pandas dataFrame
In my project I am creating a class with pandas DataFrame as core. The values ββin the dataframe depend on some specification and I initialize it with a letter representing the data I want to work with. I have put all my functions for creating the dataframe inside __init__
, as I understand that these functions are one only and are not needed for them after initialization. Also I don't want to be able to access these functions after my class is used in later code. (I'm not sure if this is the "pythonic" way to do it).
After creating a base class with methods __str__
and plotData (), I would like to apply some filters and build a new class where the extra column is the filter. I would like to do this in __init__
, but keep everything that has already been done. In other words, I don't want to rewrite the integer __init__
, I just want to add a new column to the base frame.
Similarly, I would like to add an additional plot in the plotData () function
There are already quite a few lines in my source code, but the principles are very similar to the code below.
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()
Most of the code works, at least in initialization, but I have an error when I try to create a new dataframe with an additional column. When I add a new one __init__
, I create a completely new initialization and I lose everything that was already done. I created a new function, but I would rather have an extra column after calling the new class rather than a function inside the new class. The result from the code looks like this:
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'
Question: can I partially override a superclass method to have what was previously inside this method with some new functionality? I would like to initialize myClassAv () in a dataframe with four columns instead of three like myClass (), and I would like to have myClassAv (). PlotData () to plot the third line, but keep two from the base class.
I don't know how to interpret the error and why myObject5 is None, but I suspect it is something with inheritance.
Also, if you have any suggestion that I will do things my own way, I would be grateful for hearing them.
source to share
How to simply call myClass.__init__
inside myClassAv.__init__
:
def __init__(self, frameType='All'):
myClass.__init__(self, frameType)
def addingCol(cObject):
...
addingCol(self.cObject)
To be specific,
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()
By the way, instead of
self.cObject['avarage'] = (self.cObject['c1']+self.cObject['c2']+self.cObject['c3'])/3
you can use mean(axis = 1)
:
self.cObject['average'] = self.cObject.mean(axis=1)
source to share