4

私のプロジェクトでは、パンダのDataFrameをコアとしてクラスを作成します。データフレームの値は仕様によって異なり、操作するデータを表す文字で初期化します。__init__この関数は1回限りであり、初期化後には必要ないことを理解しているので、すべての関数を内部にデータフレームを作成するために配置しました。また、クラスが後のコードで使用された後は、この関数にアクセスしたくありません。(これが「pythonic」な方法であるかどうかはわかりません)。

およびplotData()メソッドを使用して基本クラスを構築した後__str__、いくつかのフィルターを適用し、追加の列がフィルターである新しいクラスを構築したいと思います。私はそれをやりたいのですが、__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()のように3列ではなく4列のデータフレームに初期化し、myClassAv()。plotData()で3行目をプロットし、基本クラスから2列を残したいと思います。

エラーの解釈方法とmyObject5がNoneである理由はわかりませんが、継承されたものであると思われます。

また、私の考えをすべて別の方法で行うべきだという提案があれば、それを聞いていただければ幸いです。

4

1 に答える 1

6

myClass.__init__内部で呼び出すのはどうですかmyClassAv.__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)
于 2013-01-20T23:10:13.143 に答える