如何调用类中的函数?

2024-05-16 08:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中使用exchnage rate表创建一个将货币标准化为所有GBP的类。我不知道为什么我得到下面的错误。CurrencyCombo是exchnagerate表中的一个列名,我将它作为'CurrencyPairCol'传入init

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())

我想在normalize函数中应用函数remove\u char,但我不确定我是否做错了。当我按如下方式运行上述操作时:

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

我得到以下错误:

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

我认为这个错误与我如何应用remove\u char函数有关,在我尝试OOP方法之前,函数是:

def remove_char(col):#


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

我称之为:

ExchangeRate['CurrencyCombo'].apply(remove_char)

其中汇率是df。如何在类中通用函数remove_char


Tags: csv函数selfexchangeratedef错误filenameremove
1条回答
网友
1楼 · 发布于 2024-05-16 08:21:50

self表示您的类。调用self.replace()时,您正在尝试运行方法replace(该方法不存在)。你想做的是:

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

编辑:由于您正确定义了属性currencyPairCol,您只需调用:

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

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

相关问题 更多 >