首页 > 解决方案 > 计算数据框中的斜率

问题描述

这个问题只是关于计算数据帧中每个时间步的斜率。这里有很多额外的细节,欢迎您阅读或不阅读,但这一步就是我正在寻找的。

我有一个预测和一个观察到的数据框。我正在尝试计算预测中的“有趣”变化。

我想尝试通过以下方式实现:

为此,我需要在时间序列中的每个时刻生成斜率。

如何计算数据中每个点的斜率?

原来的

from sklearn import linear_model

original = series.copy() # the observations
f = y.copy() # the forecast

app = ' app_2'

original.reset_index(inplace=True)
original['date'] = pd.to_timedelta(original['date'] ).dt.total_seconds().astype(int)    

# * calculate the best fit of the observed data (ie, linear regression).
reg = linear_model.LinearRegression()

# * find its slope
reg.fit(original['date'].values.reshape(-1, 1), original[app].values)
slope = reg.coef_

# * find the difference between the slope and the slope at each moment of the observed data
delta = original[app].apply(lambda x: abs(slope - SLOPE_OF(x)))

# * calculate the stddev and mean of that difference
odm = delta.mean()
ods = delta.std(ddof=0)

# * use that to generate z-scores for the values in the forecast DF. 
# something like
f['test_delta'] = np.cumsum(f[app]).apply(lambda x: abs(slope - x))
f['z'] = f['test_delta'].apply(lambda x: x - odm / ods)

# from that I might find interesting segments of the forecast:
sig = f.index[f['z'] > 2].tolist()

标签: pythonpandas

解决方案


要“计算数据中每个点的斜率”,最简单的方法是使用Series.diff()以下方法计算每个相邻行的“上升超过运行”。结果系列给出(估计)前一行和当前行之间的瞬时变化率(IROC)。

iroc = original[app].diff() / original['date'].diff()

此外,您不需要apply. 由于 numpy 向量化,scalar - array其行为符合预期:

delta = slope - iroc

希望这有效。正如 Wen-Ben 评论的那样,查看实际数据和您的预期输出确实会有所帮助。


推荐阅读