Reputation: 10342
I am trying to index an np.array using list and np.array
indexes. But they give different result.
Here is an illustration:
import numpy as np
x = np.arange(10)
idx = [[0, 1], [1, 2]]
x[np.array(idx)] # returns array([[0, 1], [1, 2]])
but straightly apply the list gives error
x[idx] # raises IndexError: too many indices for array
I'm expecting the above returns the same result as using np.array
index.
Any ideas why?
I am using python 3.5
and numpy 1.13.1
.
Upvotes: 3
Views: 1773
Reputation: 152795
If it's an array it's interpreted as shape of the final array containing the indices - but if it's an list it's the indices along the "dimensions" (multi-dimensional array indices).
So the first example (with an array
) is equivalent to:
[[x[0], x[1],
[x[1], x[2]]
But the second example (list
) is interpreted as:
[x[0, 1], x[1, 2]]
But x[0, 1]
gives a IndexError: too many indices for array
because your x
has only one dimension.
That's because list
s are interpreted like it was a tuple, which is identical to passing them in "separately":
x[[0, 1], [1, 2]] ^^^^^^----- indices for the second dimension ^^^^^^------------- indices for the first dimension
Upvotes: 3
Reputation: 92894
From numpy indexing documentation:
ndarrays can be indexed using the standard Python
x[obj]
syntax, wherex
is the array andobj
the selection....
Basic slicing occurs when obj is a slice object (constructed bystart:stop:step
notation inside of brackets), an integer, or a tuple ofslice
objects and integers.Ellipsis
andnewaxis
objects can be interspersed with these as well. In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any non-ndarray sequence (such as alist
) containingslice
objects, theEllipsis
object, or thenewaxis
object, but not for integer arrays or other embedded sequences. ...
Upvotes: 1