Suppose I have

a = array([[1, 2],
           [3, 4]])

and

b = array([1,1])

I'd like to use b in index a, that is to do a[b] and get 4 instead of [[3, 4], [3, 4]]

I can probably do

a[tuple(b)]

Is there a better way of doing it?

Thanks

share|improve this question
    
I don't think it is a problem. why you think a[tuple(b)] is bad? – linjunhalida Apr 1 '11 at 1:44
up vote 6 down vote accepted

According the numpy tutorial:

a[tuple(b)] 

is the correct way to do this:

http://www.scipy.org/Tentative_NumPy_Tutorial#head-3f4d28139e045a442f78c5218c379af64c2c8c9e

share|improve this answer

Suppose you want to access a subvector of a with n index pairs stored in blike so:

b = array([[0, 0],
       ...
       [1, 1]])

This can be done as follows:

a[b[:,0], b[:,1]]

For a single pair index vector this changes to a[b[0],b[1]], but I guess the tuple approach is easier to read and hence preferable.

share|improve this answer
    
But which is faster I wonder? Wouldn't tuple() create a copy whereas the views above would not? – Terry Brown Sep 30 '16 at 20:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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