[英]Trying to get value in column of dataframe using another columns data using function?
I currently have a data frame "Finaldf" consisting of a column (underlying_price, strike, rate, days_to_exp, price,IV).我目前有一个数据框“Finaldf”,其中包含一列(underlying_price、strike、rate、days_to_exp、price、IV)。 that looks like this-
看起来像这样-
import pandas as pd
import mibian
stocksdf = {'underlying_price': [82600,38900,28775,28900,28275],
'strike': [30400,19050,34000,36500,34500],
'rate': [0,0,0,0,0],
'days_to_exp': [3,3,3,3,3],
'price': [12,3,4,8,3.5],
'Opt_type': ['CE', 'PE', 'PE', 'PE', 'PE']}
final=pd.DataFrame(stocksdf)
final['IV']=""
print(final)
output-输出-
underlying_price strike rate days_to_exp price Opt_type IV
0 82600 30400 3.81 3 12.0 CE
1 38900 19050 3.81 3 3.0 PE
2 28775 34000 3.81 3 4.0 PE
3 28900 36500 3.81 3 8.0 PE
4 28275 34500 3.81 3 3.5 PE
and I have a function to calculate the "ImpVol" column of "final" data frame that looks like this:我有一个 function 来计算“最终”数据框的“ImpVol”列,如下所示:
def impliedVol_Call(underlying_price, strike, rate, days_to_exp, price):
c = mibian.BS([underlying_price, strike, rate,
days_to_exp], callPrice=price)
Call_IV = c.impliedVolatility
return Call_IV
def impliedVol_Put(underlying_price, strike, rate, days_to_exp, price):
p = mibian.BS([underlying_price, strike, rate,
days_to_exp], putPrice=price)
Put_IV = p.impliedVolatility
return Put_IV
So, I tried to calculate "IV" column like this-所以,我试着像这样计算“IV”列 -
for i in range(len(final)):
if pd.isna(final["Opt_type"].iloc[i]=='CE'):
final['IV'].iloc[i]=impliedVol_Call(final['Underlying_price'][i],final['strike'][i],final['rate'][i],final['time_toEx'][i],final['Premium_price'][i])
else:
final['IV'].iloc[i]=impliedVol_Put(final['Underlying_price'][i],final['strike'][i],final['rate'][i],final['time_toEx'][i],final['Premium_price'][i])
Please help me to get the column of ImVol(IV).请帮助我获取 ImVol(IV) 列。
Well, what you are doing is in iterative manner.嗯,你正在做的是迭代的方式。 You can explore the lambdas function and apply methods over dataframe.
您可以探索 lambdas function 并在 dataframe 上应用方法。
Below is the sample code, which you can alter as per the need.下面是示例代码,您可以根据需要进行更改。 Since, i don't have your function methodology of
impliedVol_Put
, i can only suggest the method of how you can alter this.因为,我没有您的 function
impliedVol_Put
方法,我只能建议您如何改变它的方法。
final['ImpVol'] = final.apply(lambda x: impliedVol_Call(final['Underlying_price'][i],final['strike'][i],final['rate'][i],final['time_toEx'][i],final['Premium_price'][i])
if pd.isna(final["Opt_type"].iloc[i]=='CE') else impliedVol_Put(final['Underlying_price'][i],final['strike'][i],final['rate'][i],final['time_toEx'][i],final['Premium_price'][i]),
axis=1)
Maybe possible to call function impliedVol_Call inside lambda with columns as arguments.也许可以在 lambda 内调用 function impliedVol_Call,列为 arguments。
finaldf['ImpVol']=finaldf.apply(lambda x:impliedVol_Call(x[0],x[1],x[2],x[3],x[4]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.