简体   繁体   中英

apply function to array then append result to the array without loop in python

I have an array a and a list b . I want to sum values in a indexed by values in b then append it to a .

For example, a[[1,2]] = 3 + 4 = 7 then append 7 to a .

import numpy as np
a = np.array([1,3,4,5,6])
b = [[1,2], [3,4]]

for positions in b:
    tmp = a[positions].sum()
    a = np.append(a, tmp)

a 
array([ 1,  3,  4,  5,  6,  7, 11])

Could I use reduce instead of a loop?

You can use numpy.hstack :

c = np.hstack((a, a[np.r_[b]].sum(1)))

print(c)

array([ 1,  3,  4,  5,  6,  7, 11])

numpy.append , especially in a loop, is inefficient and not recommended. To see what's happening here, note that np.r_ takes an array as an input and stacks results along the first axis:

print(a[np.r_[b]])

array([[3, 4],
       [5, 6]])

We then need only sum along axis 1, and stack with the original array.

Can use np.concatenate

>>> np.concatenate([a, [a[pos].sum() for pos in b]])
array([ 1,  3,  4,  5,  6,  7, 11])

Reduce, per the documentation,

Appl[ies] function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

The salient parts are that reduce operates on pairs of inputs within the list, in sequence, and reduces the list to a single number.

Your example code only shows positions in sequence, but if that's not the case, reduce would be a bad option. Additionally, since you want to add multiple values to the original list (7 and 11), you'd have to use the reduce operation multiple times since each time only results in a single output.

You could consider instead using a list comprehension:

import numpy as np
a = np.array([1,3,4,5,6])
b = [[1,2], [3,4]]
np.append(a, [a[positions].sum() for positions in b])

a 
array([ 1,  3,  4,  5,  6,  7, 11])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM