How to update a Numpy array sequentially without l

2019-08-14 17:36发布

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)

Hence the value used to update v[i] is the updated array v. Is there a way to do these updates without a loop ?

For example,

v = [f(v, i) for i in xrange(len(v))]

does not work since the v[i-1] is not updated when it is used in the comprehensive list.

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}

it should return

v = [1, (1+2)/3, (1+4)/4, ((5/4)+4)/5, 5]

2条回答
beautiful°
2楼-- · 2019-08-14 18:04

you can use sum function for sum the numbers before v[i]:

>>> v = [v[i] + sum(v[:i]) for i in xrange(len(v))]
>>> v
[1, 3, 6, 10, 15]

or in a better way you can use np.cumsum()

>>> np.cumsum(v)
array([ 1,  3,  6, 10, 15])
查看更多
Animai°情兽
3楼-- · 2019-08-14 18:22

There is a function for this:

import numpy

v = numpy.array([1, 2, 3, 4, 5])

numpy.add.accumulate(v)
#>>> array([ 1,  3,  6, 10, 15])

This works on many different types of ufunc:

numpy.multiply.accumulate(v)
#>>> array([  1,   2,   6,  24, 120])

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)
查看更多
登录 后发表回答