Skip to main content
 首页 » 编程设计

python之使用数据帧数据调用函数会出错(无法将系列转换为 class 'float' >)

2025年05月04日9落叶无声

我有一个期权定价模型(非常简单的 Black Scholes),可以很好地处理这种方式的数据:

In [18]: 
BS2(100.,100.,1.,.001,.3) 
 
Out[18]: 
11.96762435837207 

函数在这里:

Black Sholes Function 
 
def BS2(S,X,T,r,v): 
    d1 = (log(S/X)+(.001+v*v/2)*T)/(v*sqrt(T)) 
    d2 = d1-v*sqrt(T) 
    return (S*CND(d1)-X*exp(-.001*T)*CND(d2)) 

我不认为这对这个问题很重要,但 BS2 称之为:

Cumulative normal distribution function 
 
def CND(X): 
    (a1,a2,a3,a4,a5) = (0.31938153, -0.356563782, 1.781477937,  
     -1.821255978, 1.330274429) 
    L = abs(X) 
    K = 1.0 / (1.0 + 0.2316419 * L) 
    w = 1.0 - 1.0 / sqrt(2*pi)*exp(-L*L/2.) * (a1*K + a2*K*K + a3*pow(K,3) + 
    a4*pow(K,4) + a5*pow(K,5)) 
    if X<0: 
        w = 1.0-w 
    return w 

我试图修改工作 BS 函数以接受来自 df 的数据,但似乎做错了什么:

def BS(df): 
    d1 = (log(S/X)+(.001+v*v/2)*T)/(v*sqrt(T)) 
    d2 = d1-v*sqrt(T) 
    return pd.Series((S*CND(d1)-X*exp(-.001*T)*CND(d2))) 

我的数据非常简单:

In [13]: 
df 
 
Out[13]: 
    S    X   T    r    v 
0  100  100  1  0.001  0.3 
1   50   50  1  0.001  0.3 

并且都是float64

In [14]: 
 
df.dtypes 
Out[14]: 
S    float64 
X    float64 
T    float64 
r    float64 
v    float64 
dtype: object 

我还尝试在发送到 BS2 之前将 df 变量分配给一个名称(我是这样做的,没有这个分配:

S=df['S'] 
X=df['X'] 
T=df['T'] 
r=df['r'] 
v=df['v'] 

冒着发送过多信息的风险,这里是错误信息:

In [18]: 
 
BS(df) 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-18-745e7dd0eb2c> in <module>() 
----> 1 BS(df) 
 
<ipython-input-17-b666a39cd530> in BS(df) 
  3 def BS(df): 
  4     CallPutFlag='c' 
----> 5     d1 = (log(S/X)+(.001+v*v/2)*T)/(v*sqrt(T)) 
  6     d2 = d1-v*sqrt(T) 
  7     cp = ((S*CND(d1)-X*exp(-.001*T)*CND(d2))) 
 
C:\Users\camcompco\AppData\Roaming\Python\Python34\site-   packages\pandas\core\series.py in wrapper(self) 
 74             return converter(self.iloc[0]) 
 75         raise TypeError( 
---> 76             "cannot convert the series to {0}".format(str(converter))) 
 77     return wrapper 
 78  
 
TypeError: cannot convert the series to <class 'float'> 

如有任何帮助,我们将不胜感激。

约翰

请您参考如下方法:

我认为使用 dataframe.apply() 会更容易

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html

那么语法将是 df.apply(func, axis = 1) 以将函数 func 应用于每一行。

这个问题的答案是类似的:

Apply function to each row of pandas dataframe to create two new columns