46

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

xster
  • 6,269
  • 9
  • 55
  • 60

3 Answers3

50

According the NumPy tutorial, the correct way to do it is:

a[tuple(b)]
Nicolapps
  • 819
  • 13
  • 29
JoshAdel
  • 66,734
  • 27
  • 141
  • 140
19

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.

Brandlingo
  • 2,817
  • 1
  • 22
  • 34
2

The above is correct. However, if you see an error like:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

You may have your index array in floating type. Change it to something like this:

arr[tuple(a.astype(int))]
Ruotong Jia
  • 31
  • 1
  • 3