Python 如何使用自制函数在熊猫数据帧或Numpy阵列中循环?

Python 如何使用自制函数在熊猫数据帧或Numpy阵列中循环?,python,pandas,function,loops,Python,Pandas,Function,Loops,在我的论文中,我需要期权的隐含波动率,我已经为它创建了以下函数: #Implied volatility solver def Implied_Vol_Solver(s_t,K,t,r_f,option,step_size): #s_t=Current stock price, K=Strike price, t=time until maturity, r_f=risk-free rate and option=option price,stepsize=is precision in ste

在我的论文中,我需要期权的隐含波动率,我已经为它创建了以下函数:

#Implied volatility solver
def Implied_Vol_Solver(s_t,K,t,r_f,option,step_size):
#s_t=Current stock price, K=Strike price, t=time until maturity, r_f=risk-free rate and option=option price,stepsize=is precision in stepsizes
    #sigma set equal to steps to make a step siz equal to the starting point
    sigma=step_size
    while sigma < 1:
        #Regualar BlackScholes formula (current only call option, will also be used to calculate put options)
        d_1=(np.log(s_t/K)+(r_f+(sigma**2)/2)*t)/(sigma*(np.sqrt(t)))
        d_2=d_1-np.square(t)*sigma
        P_implied=s_t*norm.cdf(d_1)-K*np.exp(-r_f*t)*norm.cdf(d_2)
        if option-(P_implied)<step_size:
            #convert stepts to a string to find the decimal point (couldn't be done with a float)
            step_size=str(step_size)
            #rounds sigma equal to the stepsize
            return round(sigma,step_size[::-1].find('.'))
        sigma+=step_size
    return "Could not find the right volatility"
然而,当我运行这个循环时,我会得到整个隐含电压列的0.539,这些数字需要不同,我错了什么?还是有更简单的解决方案

我还尝试了以下方法:

df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,np.array(df_option_data['Settlement_Price']),0.001)
df_option_data['Implied_Volatility'] = df_option_data['Settlement_Price'].apply(lambda x: Implied_Vol_Solver(100,100,1,0.01,x,0.001))
但是我得到了以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

基本上,我需要的是以下内容:一个数据框,其中5列为输入变量,1列为输出变量(隐含波动率),由函数计算。

您正在将
隐含波动率解算器的结果替换为整列,而不是特定的单元格

请尝试以下操作:

df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,np.array(df_option_data['Settlement_Price']),0.001)
df_option_data['Implied_Volatility'] = df_option_data['Settlement_Price'].apply(lambda x: Implied_Vol_Solver(100,100,1,0.01,x,0.001))

apply
函数可以将一个函数应用于数据列中的所有元素,这样您就不需要自己为
循环执行

您可以将行(作为一个系列)中的值传递到函数中,而不是将输入变量传递到函数中。然后,使用apply函数获取输出帧。这看起来像这样:

def Implied_Vol_Solver(row):
    s_t = row['s_t']  # or whatever the column is called in the dataframe
    k = row['k']  # and so on and then leave the rest of your logic as is
df_option_data['Implied_Volatility'] = df_option_data.apply(Implied_Vol_Solver, axis=1)
修改函数后,可以如下方式使用它:

def Implied_Vol_Solver(row):
    s_t = row['s_t']  # or whatever the column is called in the dataframe
    k = row['k']  # and so on and then leave the rest of your logic as is
df_option_data['Implied_Volatility'] = df_option_data.apply(Implied_Vol_Solver, axis=1)

首先感谢您的快速回复,我理解ATK7474解决方案,但您的解决方案更易于应用和维护。一个小问题是,其他变量也需要更改,如何使用多个参数执行Lambda函数?目前我只能调整一个变量,但所有五个变量都需要更改(变量在同一行,但列不同)。@10uss您可以看看: