繁体   English   中英

如何获取Python数据框中多列的斜率

[英]how to get the slope of multiple columns in Python data frame

我有下面的数据框,其中包含 4 列分数。 我如何找到数据框中每个单独 ID 的这 4 个分数的斜率?

ID  t1  t2  t3  t4
a   1   2   3   4
b   3   2   1   
c   4   2   1   2
d   2   3   4   5
e   0   2   3   4

我希望将斜率附加到相同的数据框并在计算斜率后显示以下内容。

ID  Slope
a   1
b   -1
c   -0.7
d   1
e   1.3

你可以为此使用sklearn (或者可能是scipy )。 例子:

import sklearn

model = sklearn.linear_model.LinearRegression()
def get_coeff(row, model=model):
    # fit a row assuming points are separated by unit length and return the slope.
    
    row = row.copy().dropna()
    model.fit(np.arange(len(row)).reshape(-1,1), row.values.reshape(-1,1))
    slope = model.coef_[0][0]
    return slope


df["slope"] = df.apply(get_coeff, axis=1)

output:

    t1  t2  t3   t4  slope
ID
a    1   2   3  4.0    1.0
b    3   2   1  NaN   -1.0
c    4   2   1  2.0   -0.7
d    2   3   4  5.0    1.0
e    0   2   3  4.0    1.3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM