1

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 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

This method works well if the v at the index i is updated using only the index i-1. But it does not work with a function like f(v[i]) = v[i-1] + v[i] + v[i+1], since accumulate needs only function with two arguments.
I edited my question to add the case where f has three arguments.
@haron You should probably ask a new question instead.
1

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])

1 Comment

Considering Numpy's use in large arrays, O(n²) algorithms are actually going to be worse than a pure-python loop, and this isn't even vectorized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.