如何计算每列滚动(window=60)值的斜率,步长为 5?
我想每 5 分钟计算一次值,我不需要每条记录的结果。
这是示例数据框和结果:
df
Time A ... N
2016-01-01 00:00 1.2 ... 4.2
2016-01-01 00:01 1.2 ... 4.0
2016-01-01 00:02 1.2 ... 4.5
2016-01-01 00:03 1.5 ... 4.2
2016-01-01 00:04 1.1 ... 4.6
2016-01-01 00:05 1.6 ... 4.1
2016-01-01 00:06 1.7 ... 4.3
2016-01-01 00:07 1.8 ... 4.5
2016-01-01 00:08 1.1 ... 4.1
2016-01-01 00:09 1.5 ... 4.1
2016-01-01 00:10 1.6 ... 4.1
....
result
Time A ... N
2016-01-01 00:04 xxx ... xxx
2016-01-01 00:09 xxx ... xxx
2016-01-01 00:14 xxx ... xxx
...
df.rolling 函数可以用来解决这个问题吗?
如果 NaN 在窗口中就没问题,这意味着子集可以小于 60。
最佳答案
看来你想要的是以特定步长滚动。
然而,根据documentation of pandas ,rolling
目前不支持步长。
如果数据量不是太大,只需对所有数据进行滚动,然后使用索引选择结果。
这是一个示例数据集。为简单起见,时间列使用整数表示。
data = pd.DataFrame(np.random.rand(500, 1) * 10, columns=['a'])
a
0 8.714074
1 0.985467
2 9.101299
3 4.598044
4 4.193559
.. ...
495 9.736984
496 2.447377
497 5.209420
498 2.698441
499 3.438271
然后,滚动并计算斜率,
def calc_slope(x):
slope = np.polyfit(range(len(x)), x, 1)[0]
return slope
# set min_periods=2 to allow subsets less than 60.
# use [4::5] to select the results you need.
result = data.rolling(60, min_periods=2).apply(calc_slope)[4::5]
结果是,
a
4 -0.542845
9 0.084953
14 0.155297
19 -0.048813
24 -0.011947
.. ...
479 -0.004792
484 -0.003714
489 0.022448
494 0.037301
499 0.027189
或者,您可以引用这篇文章。第一个答案提供了一种实现此目的的 numpy 方法: step size in pandas.DataFrame.rolling
关于python - Pandas - 滚动斜率计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42138357/