about fancy indexing in numpy, like `a[b]` or `a[np.array(b)]`, b is a list. the result is different

Viewed 40

there is someting confusing me:

a = np.array([7,8,9,10])
b=[[3,1],[1,2]]
print(a[b])
"""
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
"""

but transform b=[[3,1],[1,2]] to:

b=np.array([[3,1],[1,2]])
print(a[b])
"""
array([[10, 8],
       [ 8, 9]])
"""

okay, someone know why b must be a ndarray instead of list? thanks.

1 Answers

In a new enough numpy version we get a warning along with the error:

In [113]: a = np.array([7,8,9,10])
     ...: b=[[3,1],[1,2]]
In [114]: a[b]
<ipython-input-114-48d1ef76a37c>:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; 
use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, 
which will result either in an error or a different result.
  a[b]
Traceback (most recent call last):
  File "<ipython-input-114-48d1ef76a37c>", line 1, in <module>
    a[b]
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

So historically some lists of lists were interpreted as:

In [115]: a[tuple(b)]
Traceback (most recent call last):
  File "<ipython-input-115-b78d8d2bd7a8>", line 1, in <module>
    a[tuple(b)]
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

The desired array interpretation:

In [116]: a[np.array(b)]
Out[116]: 
array([[10,  8],
       [ 8,  9]])
Related