私信  •  关注

anon01

anon01 最近创建的主题
anon01 最近回复了
3 年前
回复了 anon01 创建的主题 » python:解析以冒号分隔的格式化字符串

像这样的方法应该有用:

ss = "1:4:a:5:6:7:2:10:72:75:63:6f:6e:74:72:6f:6c:6c:65:72:2e:6f:72:67".split(":")

d = {}
idx = 0
while idx < len(ss):
    key = ss[idx]
    idx += 1
    length = int(ss[idx])
    idx += 1
    arr = ss[idx:idx+length]
    d[key] = arr
    idx += length

输出 d :

{'1': ['a', '5', '6', '7'],
 '2': ['72', '75', '63', '6f', '6e', '74', '72', '6f', '6c', '6c'],
 '65': ['2e', '6f', '72', '67']}
3 年前
回复了 anon01 创建的主题 » 如何在Python数据框架中获取多列的斜率

你可以用 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