我希望在condrolmax
(基于close
)列(条件滚动/累计最大值)中实现以下结果,而不使用愚蠢的慢速for循环
Index close bool condrolmax
0 1 True 1
1 3 True 3
2 2 True 3
3 5 True 5
4 3 False 5
5 3 True 3 --> rolling/accumulative maximum reset (False cond above)
6 4 True 4
7 5 False 4
8 7 False 4
9 5 True 5 --> rolling/accumulative maximum reset (False cond above)
10 7 False 5
11 8 False 5
12 6 True 6 --> rolling/accumulative maximum reset (False cond above)
13 8 True 8
14 5 False 8
15 5 True 5 --> rolling/accumulative maximum reset (False cond above)
16 7 True 7
17 15 True 15
18 16 True 16
创建此数据帧的代码:
# initialise data of lists.
data = {'close':[1,3,2,5,3,3,4,5,7,5,7,8,6,8,5,5,7,15,16],
'bool':[True, True, True, True, False, True, True, False, False, True, False,
False, True, True, False, True, True, True, True],
'condrolmax': [1,3,3,5,5,3,4,4,4,5,5,5,6,8,8,5,7,15,16]}
# Create DataFrame
df = pd.DataFrame(data)
我相信这是可能的矢量化(一个线性)。有什么建议吗
再次感谢
我不确定我们如何使用线性代数和矢量化来加快这个函数的速度,但是使用列表理解,我们编写了一个更快的算法。首先,将函数定义为:
然后,您可以使用:
要添加和加载line profiler并查看每行代码需要多长时间,请执行以下操作:
这将导致: Each line profiling results
当然,看看整个功能需要多长时间:
这将导致: Total algorithm profiling result
如果你使用SeaBean函数,你可以得到更好的结果,速度是我建议的函数的一半。然而,SeaBean的估计速度似乎并不稳定,要估计他的函数,您应该在更大的数据集上运行它,然后再决定。这都是因为%timeit报告如下: SeaBean's function profiling result
首先使用您的条件(bool从False变为True)和
cumsum
创建组,然后在groupby
之后应用rolling
:输出:
要作为列插入,请执行以下操作:
输出:
NB。如果希望滚动中包括边界,请在
rolling
中使用min_periods=1
您可以设置组,然后使用^{} ,如下所示:
结果:
相关问题 更多 >
编程相关推荐