簡體   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