1

So given a 1D array like

x = np.array([0,1,2,3,4,5,6,7,8,9])

I want to index multiple elements at the same time. For example instead of

x[1]
x[2]

I want to use

x[(1,2)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array

It works for 1 2D array like for example

x = np.array([[1,2,3,4],[5,6,7,8],[7,6,8,9]])
>>> x
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [7, 6, 8, 9]])
>>> x[(1,2),(1,3)]
array([6, 9])
>>> x[(1,2),:]
array([[5, 6, 7, 8],
       [7, 6, 8, 9]])

So as you can see, for nd-arrays it works fine! Any way to do this kind of indexing for 1d-arrays?

2 Answers 2

3

You need to wrap the indices in a list, not a tuple: x[[1,2]]. This triggers advanced indexing and NumPy returns a new array with the values at the indices you've written.


Whenever possible, NumPy implicitly assumes that each element of a tuple indexes a different dimension of the array. Your array has 1 dimension, not 2, hence x[(1,2)] raises an error.

The reason x[(1,2), :] succeeds with a 2D array is that you've explicitly told NumPy that the array has (at least) two dimensions and said what you want from the first two axes. The index is parsed as the 2-tuple ((1,2), :) so (1,2) is instead used for advanced indexing along the first axis. Had you simply used x[(1,2)] or x[1,2], you would get a single element at row 1, column 2.

Parsing the index is very complicated for NumPy because (unlike Python) there are several different indexing methods that can be used. To complicate things further, different methods may be used on different axes! You can study the exact implementation in NumPy's mapping.c file.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to put the indices in a list not tuple,numpy use tuples for indexing multi-dimensional arrays :

>>> x[[1,2]]
array([1, 2])

>>> x[(1,2)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices

Another example :

>>> x = np.array([6,4,0,8,77,11,2,12,67,90])
>>> x[[6,0]]
array([2, 6])

1 Comment

to alleviate the problem with tuples vs lists, etc. writing x[[*idx]] that first "explodes" the index array and then "repackages" a list; works at least with idx being a tuple, a list and np.array

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.