问题描述
我有一个数组:
A = np.array([2,3,5,8,3,5])
什么是最有效的(矢量)的方式,其中每个元素结果是计算一个数组(伪code):
结果[0] = A [0]
对于i GT; 0:
结果由[i] =导致[I-1] +(一个[I] - 结果[I-1])*因子
我可以用下面的低效code做到这一点(系数= 0.5):
A = np.array([2,3,5,8,3,5])
结果= np.array([一个[0])
对于k在[1:]:
结果= np.append(结果是,导致[-1] +(K-结果[-1])* 0.5)
这减震功能的结果将是:
阵列([2,2.5,3.75,5.875,4.4375,4.71875])
您是正在寻找Haskell的的选择:
prelude> scanl1(\\ A B - >一种+(B - A)* 0.5)[2,3,5,8,3,5]
[2.0,2.5,3.75,5.875,4.4375,4.71875]
有一个功能:
在[1]:进口和itertools在[2]:itertools.accumulate([2,3,5,8,3,5],拉姆达的a,b:一个+(B - A)* 0.5)
出来[2]:其中,在itertools.accumulate&0x7f1fc1fc1608 GT;在[3]:列表(itertools.accumulate([2,3,5,8,3,5],拉姆达的a,b:一个+(B - A)* 0.5))
出[3]:[2,2.5%,3.75,5.875,4.4375,4.71875]
使用numpy的你可以使用功能,但根据,有在执行中的错误,这就是为什么我们应该使用一个演员。不幸的是,我不是很熟悉numpy的,并且,也许有更好的方式:
在[9]:进口numpy的为NP在[10]:UF = np.frompyfunc(拉姆达的a,b:一个+(B - A)* 0.5,2,1)在[11]:uf.accumulate([2,3,5,8,3,5],DTYPE = np.object).astype(np.float)
出[11]:阵列([2,2.5,3.75,5.875,4.4375,4.71875])
I have an array:
a = np.array([2,3,5,8,3,5])
What is the most efficient (vectorized) way to calculate an array where each resulting element is (Pseudocode):
result[0] = a[0]
for i > 0:
result[i] = result[i-1] + (a[i] - result[i-1]) * factor
I could do this with the following inefficient code (factor = 0.5):
a = np.array([2,3,5,8,3,5])
result = np.array([a[0]])
for k in a[1:]:
result = np.append(result, result[-1]+(k-result[-1])*0.5)
The result of this damping function would be:
array([ 2., 2.5, 3.75, 5.875, 4.4375, 4.71875])
You a looking for Haskell's scanl1
alternative in Python (Haskell example):
Prelude> scanl1 (\a b -> a + (b - a) * 0.5) [2, 3, 5, 8, 3, 5]
[2.0,2.5,3.75,5.875,4.4375,4.71875]
There is an accumulate
function in itertools
module:
In [1]: import itertools
In [2]: itertools.accumulate([2, 3, 5, 8, 3, 5], lambda a, b: a + (b - a) * 0.5)
Out[2]: <itertools.accumulate at 0x7f1fc1fc1608>
In [3]: list(itertools.accumulate([2, 3, 5, 8, 3, 5], lambda a, b: a + (b - a) * 0.5))
Out[3]: [2, 2.5, 3.75, 5.875, 4.4375, 4.71875]
With NumPy you may use numpy.ufunc.accumulate
function, however, according to this answer, there is a bug in the implementation, that is why we should use a cast. Unfortunately, I'm not very familiar with NumPy, and, probably, there is a better way:
In [9]: import numpy as np
In [10]: uf = np.frompyfunc(lambda a, b: a + (b - a) * 0.5, 2, 1)
In [11]: uf.accumulate([2,3,5,8,3,5], dtype=np.object).astype(np.float)
Out[11]: array([ 2. , 2.5 , 3.75 , 5.875 , 4.4375 , 4.71875])
这篇关于如何申请到数组的每个元素的功能时,其结果取决于preceding细胞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!