如何顺序更新Numpy数组而无循环 [英] How to update a Numpy array sequentially without loop
问题描述
我有一个Numpy数组 v ,我想使用该数组当前元素上的函数来更新每个元素:
I have a Numpy array v and I want to update each element using a function on the current element of the array :
v[i] = f(v, i)
执行此操作的基本方法是使用循环
A basic way to do this is to use a loop
for i in xrange(2, len(v)):
v[i] = f(v, i)
因此,用于更新 v [i] 的值就是更新后的数组 v .有没有办法进行这些更新而没有循环?
Hence the value used to update v[i] is the updated array v. Is there a way to do these updates without a loop ?
例如
v = [f(v, i) for i in xrange(len(v))]
不起作用,因为在综合列表中使用 v [i-1] 时不会对其进行更新.
does not work since the v[i-1] is not updated when it is used in the comprehensive list.
I函数 f 可以取决于列表中的几个元素,索引应小于i的那些元素应被更新,而索引大于i的那些元素尚未被更新,如以下示例所示:
IThe function f can depend on several elements on the list, those with index lower than i should be updated and those with an index greater than i are not yet updated, as in the following example :
v = [1, 2, 3, 4, 5]
f = lambda v, i: (v[i-1] + v[i]) / v[i+1] # for i = [1,3]
f = lambda v, i: v[i] # for i = {0,4}
它应该返回
v = [1, (1+2)/3, (1+4)/4, ((5/4)+4)/5, 5]
推荐答案
为此提供了一个功能:
import numpy
v = numpy.array([1, 2, 3, 4, 5])
numpy.add.accumulate(v)
#>>> array([ 1, 3, 6, 10, 15])
这适用于许多不同类型的ufunc
:
This works on many different types of ufunc
:
numpy.multiply.accumulate(v)
#>>> array([ 1, 2, 6, 24, 120])
对于执行这种累加的任意函数,您可以创建自己的ufunc
,尽管这会慢很多:
For an arbitrary function doing this kind of accumulation, you can make your own ufunc
, although this will be much slower:
myfunc = numpy.frompyfunc(lambda x, y: x + y, 2, 1)
myfunc.accumulate([1, 2, 3], dtype=object)
#>>> array([1, 3, 6], dtype=object)
这篇关于如何顺序更新Numpy数组而无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!