2017-10-15 190 views
0

我试图在数据框中的两个字段的单个子集上添加斜率计算,并将斜率值应用于每个子集中的所有行。 (我之前在excel中使用过“斜率”函数,尽管我并没有结婚到准确的算法,“desired_output”字段就是我期望的输出结果,子集由“strike_order”列,子集从1开始,而不是具有特定的最高值。从pandas df生成“最佳拟合”斜率梯度并填充新列b

“IV”是y值 “罢工”是x值

任何帮助,将不胜感激,因为我不知道在哪里具有此开始....

import pandas 
df = pandas.DataFrame([[1200,1,.4,0.005],[1210,2,.35,0.005],[1220,3,.3,0.005], 
[1230,4,.25,0.005],[1200,1,.4,0.003],[1210,2,.37,.003]],columns= 
["strike","strike_order","IV","desired_output"]) 
df 

    strike strike_order IV desired_output 
0 1200  1   0.40 0.005 
1 1210  2   0.35 0.005 
2 1220  3   0.30 0.005 
3 1230  4   0.25 0.005 
4 1200  1   0.40 0.003 
5 1210  2   0.37 0.003 

让我知道这是不是一个很好的问题提出,我会尽量做到更好。

回答

0

您可以使用numpy's least square 我们可以重写线方程y=mx+cy = Ap,其中A = [[x 1]]p = [[m], [c]]。然后使用lstsq解决了P,所以我们需要通过添加构成的列,共创的df,

import numpy as np 
df['ones']=1 
A = df[['strike','ones']] 
y = df['IV'] 
m, c = np.linalg.lstsq(A,y)[0] 

或者您可以使用scikit学习的linear_model回归模型

您可以通过绘制验证结果数据作为散点图和线性方程为曲线

import matplotlib.pyplot as plt 
plt.scatter(df['strike'],df['IV'],color='r',marker='d') 
x = df['strike'] 
#plug x in the equation y=mx+c 
y_line = c + m * x 
plt.plot(x,y) 
plt.xlabel('Strike') 
plt.ylabel('IV') 
plt.show() 

所得曲线表示下面 enter image description here

+0

非常感谢,因为它让我成为那里的一部分。 –

0

试试这个。

首先通过遍历数据帧,使用strike_order值转变创建一个子集柱为1,子集之间的边界

#create subset column 
subset_counter = 0 
for index, row in df.iterrows(): 
    if row["strike_order"] == 1: 
     df.loc[index,'subset'] = subset_counter 
     subset_counter += 1 
    else: 
     df.loc[index,'subset'] = df.loc[index-1,'subset'] 

df['subset'] = df['subset'].astype(int) 

然后,使用GROUPBY

# run linear regression on subsets of the dataframe using groupby 
from sklearn import linear_model 
model = linear_model.LinearRegression() 
for (group, df_gp) in df.groupby('subset'): 
    X=df_gp[['strike']] 
    y=df_gp.IV 
    model.fit(X,y) 
    df.loc[df.subset == df_gp.iloc[0].subset, 'slope'] = model.coef_ 

df 

    strike strike_order IV desired_output subset slope 
0 1200    1 0.40   0.005  0 -0.005 
1 1210    2 0.35   0.005  0 -0.005 
2 1220    3 0.30   0.005  0 -0.005 
3 1230    4 0.25   0.005  0 -0.005 
4 1200    1 0.40   0.003  1 -0.003 
5 1210    2 0.37   0.003  1 -0.003 
+0

你在煤矿开采中被浪费了。 –

0
辗过每个子集的线性回归

@ Scott除了子集值为0,1以外,其他所有子集的值都是2.我在开头添加了一个额外的条件,并且使用非常笨拙的种子“seed”值来停止查找第-1行。

import scipy 
    seed=df.loc[0,"date_exp"] 
    #seed ="08/11/200015/06/2001C" 
    #print(seed) 
    subset_counter = 0 
    for index, row in df.iterrows(): 
     #if index['strike_order']==0: 
     if row['date_exp'] ==seed: 
     df.loc[index,'subset']=0 

     elif row["strike_order"] == 1: 
     df.loc[index,'subset'] = subset_counter 
     subset_counter = 1 + df.loc[index-1,'subset'] 
     else: 
      df.loc[index,'subset'] = df.loc[index-1,'subset'] 

    df['subset'] = df['subset'].astype(int) 

现在,这不正是我想要的东西,虽然我认为使用该种子值是笨重的,宁愿如果row == 0等使用,但它是星期五和工作原理。

干杯