首页 > 解决方案 > How do I call a function within my class?

问题描述

I'm trying to practice classes in python by trying to make a class which normalizes the currency to all GBP using an exchnage rate table. I'm not sure why i'm getting the below error. CurrencyCombo is a column name in the exchnagerate table which i pass into init as 'CurrencyPairCol'

rateList = ['EURGBP','USDGBP', 'SEKGBP']
Month = ['2018-11', '2018-12', '2019-01', '2019-02', '2019-03']

class CurrencyNormalize():

    def __init__(self,filename,rateList,monthList,orders_filename,CurrencyPair):
        self.ExchangeRate = pd.read_csv(filename)
        self.OrdersTrain = pd.read_csv(orders_filename)
        self.rateList=rateList
        self.monthList=monthList
        self.currencyPairCol=self.ExchangeRate[CurrencyPair]

    def remove_char(self):

        return (self.replace('GBP', ''))


    def normalize(self):
        ExchangeRateFilt= self.ExchangeRate[self.ExchangeRate.CurrencyCombo.isin(self.rateList)]
        monthOnly= ExchangeRateFilt[ExchangeRateFilt.TradeMonth.isin(self.monthList)]
        print(monthOnly['CurrencyCombo'])
        monthOnly['CurrencyCombo] = monthOnly['CurrencyCombo].apply(self.remove_char())

I want to apply the function remove_char in the normalize function but i'm not sure if i'm doing it wrong. WHen i run the above as follows:

CurrencyNormalize('MonthlyExchangeRates.csv',rateList,Month,'Orderss.csv','CurrencyCombo').normalize() 

I get the following error:

AttributeError: 'CurrencyNormalize' object has no attribute 'replace'

I think the error has something to do with how i appply the remove_char function, before i tried the OOP way the function was:

def remove_char(col):#


    return (col.replace('GBP', ''))

and i would call it as :

ExchangeRate['CurrencyCombo'].apply(remove_char)

where Exchange rate is the df. How do i generalilse the function remove_char within the class?

标签: pythonpandasoop

解决方案


self指你的班级。当您打电话时,self.replace()您正在尝试运行该方法replace(该方法不存在)。你想要做的是这样的:

self.ExchangeRate[CurrencyPair].replace('GBP', '')

编辑:由于您正确定义了属性currencyPairCol,您可以简单地调用:

self.currencyPairCol.replace('GBP', '')

显然,后者只会修改属性currencyPairCol而不是最初导入的数据框ExchangeRate(也不是其中的列CurrencyPair


推荐阅读