你可以用
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)
输出:
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