0

I'm just starting out with numpy and can't find a simple solution to this problem.

Simple example:

import numpy as np

A = np.array([[1, 2], [-1, 5], [0, 12]])
x1 = (0, 0)
x2 = (1, 1)
x3 = (2, 0)
A[x1]  # 1
A[x2]  # 5
A[x3]  # 0

I'd like to somehow put my tuples x1, x2, x3 into a single object, which I would then use to index into A. I'd like this to return [1, 5, 0] -- hence the title, accessing multiple (row, column) combinations in a numpy array. Is there an easy way to do this?

Here's what I've tried:

A[[x1, x2, x3]]  # IndexError
A[(x1, x2, x3)]  # IndexError
A[x1, x2, x3]  # IndexError
A[np.array((x1, x2, x3))]  # Not what I'm trying to do

One possibility is:

tuples = (x1, x2, x3)
elems = []
for tup in tuples:
    elems.append(A[tup])

B = np.array(elems)
B  # [1, 5, 0] as desired

But is there a way to avoid the loop?

1 Answer 1

3
In [1357]: A[zip(x1,x2,x3)]
Out[1357]: array([1, 5, 0])

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.