python - 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?
解决方案
self
指你的班级。当您打电话时,self.replace()
您正在尝试运行该方法replace
(该方法不存在)。你想要做的是这样的:
self.ExchangeRate[CurrencyPair].replace('GBP', '')
编辑:由于您正确定义了属性currencyPairCol
,您可以简单地调用:
self.currencyPairCol.replace('GBP', '')
显然,后者只会修改属性currencyPairCol
而不是最初导入的数据框ExchangeRate
(也不是其中的列CurrencyPair
)
推荐阅读
- angular - 如果没有子下拉菜单,则停止显示primeng下拉菜单
- c++ - VS2017调试模式下OpenCV中的“错误分配”
- r - 在 Windows 10 上将带有西班牙语字符的数据框加载到 RStudio
- java - Java 正则表达式跳过某些字符仅匹配一次出现的数字,并带有间歇性句点
- nativescript - Nativescript sidekick 最新更新(版本:1.14.1-v.2018.11.23.3(最新))
- google-app-maker - 如何在 Google 应用制作工具中更新相关数据模型中的记录
- javascript - 如何将 Jison 生成的解析器包含到 Angular 中?
- android - 创建一个 .sh 脚本到 ADB 安装一些 APK
- php - Wordpress - 提交完成后发送消息
- java - java - 为什么我的矩阵不能正常工作?