Issue
I have 3-dimensional numpy array
a = np.array([
[
[1, 3],
[0, 2]
],
[
[2, 1],
[4, 2]
]
], dtype=np.int32)
And I want to get the elements using the indices [0, 1, 1], and [1, 0, 1]
which I expect to give me:
[2, 1]
If I index with list, it returns the result I wanted, but if I index with Numpy array, it gives different results, why is that?
>>> indices = [[0, 1], [1, 0], [1, 1]]
>>> indices_arr = np.array(indices, dtype=np.int32)
>>> a[indices]
# OUTPUT
# array([2, 1], dtype=int32
>>> a[indices_arr]
# OUTPUT
'''
array([[[[1, 3],
[0, 2]],
[[2, 1],
[4, 2]]],
[[[2, 1],
[4, 2]],
[[1, 3],
[0, 2]]],
[[[2, 1],
[4, 2]],
[[2, 1],
[4, 2]]]], dtype=int32)
'''
Solution
In a current numpy version indices
gives a warning:
In [46]: a[indices_arr].shape
Out[46]: (3, 2, 2, 2)
In [47]: a[indices]
C:\Users\paul\AppData\Local\Temp\ipykernel_8668\2035022355.py: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[indices]
Out[47]: array([2, 1])
doing the tuple conversion myself:
In [48]: a[tuple(indices)]
Out[48]: array([2, 1])
Your indices_arr
is the different result it warns about.
With tuple, we are applying each sublist to a separate dimension of
a`:
In [49]: a[[0, 1], [1, 0], [1, 1]]
Out[49]: array([2, 1])
With indices_arr
, the array is applied to just the first dimension, hence the (2,) becomes (3,2).
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.