如何将数据框传递给对象的方法?

问题描述:

为什么此代码会给出以下错误?如何将数据框传递给对象的方法?

TypeError: simple_returns() takes 1 positional argument but 2 were given

import datetime as dt 
import math 
from matplotlib import style 
import numpy as np 
import pandas as pd 
import pandas_datareader.data as web 

start = dt.datetime(2000, 1, 1) 
end = dt.datetime(2016, 12, 31) 

df = web.DataReader('TSLA', 'yahoo', start, end) 


class CalcReturns: 
    def simple_returns(self): 
     simple_ret = self.pct_change() 
     return simple_ret 

    def log_returns(self): 
     simple_ret = self.pct_change() 
     log_ret = np.log(1 + simple_ret) 
     return log_ret 


myRet = CalcReturns() 
c = df['Adj Close'] 
sim_ret = myRet.simple_returns(c) 
print(sim_ret) 

只需添加到类的方法的参数来接收pandas.Series并确保应用pct_change()方法的系列而不是类对象self

class CalcReturns: 
    def simple_returns(self, ser): 
     simple_ret = ser.pct_change() 
     return simple_ret 

    def log_returns(self, ser): 
     simple_ret = ser.pct_change() 
     log_ret = np.log(1 + simple_ret) 
     return log_ret 


myRet = CalcReturns() 
c = df['Adj Close'] 
sim_ret = myRet.simple_returns(c) 
print(sim_ret) 

# Date 
# 2010-06-29   NaN 
# 2010-06-30 -0.002511 
# 2010-07-01 -0.078473 
# 2010-07-02 -0.125683 
# 2010-07-06 -0.160937 
# 2010-07-07 -0.019243 
# 2010-07-08 0.105063 
# 2010-07-09 -0.003436 
# 2010-07-12 -0.020115 
+0

谢谢Parfait。你是对的。伟大的图标! – Leigh

线:

sim_ret = myRet.simple_returns(c) 

呼叫CalcReturns.simple_returns()并且似乎仅传递一个参数。但是python类的方法是特殊的,因为python也传递对象本身。它在第一个参数中执行此操作。这就是你看到这个模式的原因:

class MyClass(): 

    def my_method(self): 
     """ a method with no parameters, but is passed the object itself """ 

self名为自按照惯例提醒我们,它是对象。所以,如果你想通过你的数据框,您将需要更改方法签名的样子:

def simple_returns(self, a_df): 
+0

谢谢。这hleps – Leigh