>>> import numpy as np
>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> # The first indexing
>>> a[:, np.array([1, 3])]
array([[ 1, 3],
[ 5, 7],
[ 9, 11]])
>>> # The second indexing
>>> a[np.newaxis][0, :, np.array([1, 3])]
array([[ 1, 5, 9],
[ 3, 7, 11]])
In which I expected the returned shape of the second indexing should also be (3, 2), but it is somehow "transposed".
I found a simillar question here:
Implicit transposing in numpy array indexing
According to the answer, I may change the advanced indexing to the basic indexing, i.e.,
>>> # The second indexing
>>> a[np.newaxis][0, :, 1::2]
array([[ 1, 3],
[ 5, 7],
[ 9, 11]])
However, in some cases, I have to (or prefere to) use advanced indexings.
For example, I have a colored voxel data of shape (Batch, Channel, X, Y, Z)
(for PyTorch), where the channel is 3 (R, G, B
). Now I want to query N points by an N*3
array.
>>> voxel = np.random.random((1, 3, 2, 2, 2))
>>> query = np.array([
... [0, 0, 1],
... [1, 0, 1],
... ])
>>> voxel[0, :, query[:, 0], query[:, 1], query[:, 2]]
array([[0.72319319, 0.77342985, 0.09089421],
[0.84757841, 0.90991516, 0.84755281]])
where I expect the result to be of shape (3, 2)
Is there any suggestion then?