I'm trying to understand numpy fancy indexing. I still cannot differentiate the usage between np.array(...)
and plain-old python list [...]
passing into the (only) square-brackets of arr
where arr
is a np.array
. Here is the concrete example I'm using to learn by doing:
import numpy as np
print("version: %s" % np.__version__) # this prints 1.22.3
x = np.arange(10)
print(x)
print([x[3], x[7], x[2]])
print("---- x[ind_1d], ind_1d=[3,7,2]")
ind_1d = np.array([3, 7, 2])
ind_1d = [3, 7, 2]
print(x[ind_1d])
print("---- x[ind_2d], ind_2d=[[3,7],[4,5]]")
ind_2d = np.array([[3, 7], [4, 5]])
# ind_2d = [[3, 7], [4, 5]]
print(x[ind_2d], end="\n\n")
This program can run without any error/warning that I will mention below. But if I uncomment the line # ind_2d = [[3, 7], [4, 5]]
then I will get a warning:
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.
and an error:
Traceback (most recent call last):
File ".../index.py", line 14, in <module>
print(x[ind_2d], end="\n\n")
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
update: what I've tried:
- If I set
ind_2d = [3,7],[4,5]
, so I'm changinglist
totuple
I still got the error. - If I set
ind_2d = [[3,7],[4,5]],
, so I'm adding an extra-layer tuple, then the program run without any error and warning.
Can anyone provide some rules to follow I can avoid these kinds of errors and/or warnings?