我想加速这个代码:
import numpy as np
import pandas as pd
a = pd.read_csv(path)
closep = a['Clsprc']
delta = np.array(closep.diff())
upgain = np.where(delta >= 0, delta, 0)
downloss = np.where(delta <= 0, -delta, 0)
up = sum(upgain[0:14]) / 14
down = sum(downloss[0:14]) / 14
u = []
d = []
for x in np.nditer(upgain[14:]):
u1 = 13 * up + x
u.append(u1)
up = u1
for y in np.nditer(downloss[14:]):
d1 = 13 * down + y
d.append(d1)
down = d1
数据如下:
^{pr2}$for循环太慢,我能做些什么来加速这个代码?我能把整个操作矢量化吗?在
看起来你在试图计算指数移动平均数(滚动平均数),但忘记了除法。如果是这样的话,你可能想看看thisSO问题。同时,这里有一个快速的简单移动平均值,它使用来自被引用链接的
cumsum()
函数。在如果不是这样,并且您确实希望描述函数,那么可以通过在迭代中使用
^{pr2}$external_loop
标志来提高迭代速度。从numpy文档中:简而言之,我认为这就是循环的作用:
制作:
^{pr2}$这里有
np.cumprod([10,10,10,10])
,加上[.1,.2,.3,.4]
项的修改后的cumsum
。但是我不能马上想到一种将这些函数与编译的numpy
函数相结合的方法。我们可以编写一个自定义的ufunc
,并使用它的accumulate
。或者我们可以在cython
(或其他c
接口)中编写它。在https://stackoverflow.com/a/27912352表明
frompyfunc
是一种编写广义accumulate
的方法。我不希望节省很多时间,也许是2倍要使用
frompyfunc
,请定义:循环应用程序(上面)将是
“矢量化”版本为:
dtype=object
需求已在前面的SO中指出,并且https://github.com/numpy/numpy/issues/4155对于这个小列表,
loopfoo
更快(3µs v 21µs)对于100元素数组,例如
biggain=np.linspace(.1,1,100)
,vfoo.accumulate
更快:对于更大的
biggain=np.linspace(.001,.01,1000)
(为避免溢出,较小的数字),5x速比仍然存在。在相关问题 更多 >
编程相关推荐