FranGoitia
FranGoitia

Reputation: 1993

numpy. Sum multidimensional array at specific indexes

I'm trying to replace something like this code, for a vectorized efficient operation using numpy.

counter = 0
idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
for l in lists:
    for idx in idxs:
        counter += l[idx]

Upvotes: 0

Views: 459

Answers (1)

Daniel
Daniel

Reputation: 42748

Just sum the array:

idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
ary = np.array(lists)
counter = ary[:,idxs].sum()

Upvotes: 1

Related Questions