1
>>> 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?

Yinda Yin
  • 31
  • 4
  • I think my answers (2) cover the issue well enough – hpaulj Feb 05 '21 at 04:44
  • Given that the second index is exactly the same as in the other question, I have to close this as a duplicate. The answer is going to be the same OP's failure to understand it does not alter the content. – Mad Physicist Feb 05 '21 at 05:53
  • The only subtle difference is that instead of the slice `:5`, the answer here would be something like `1::2`. – Mad Physicist Feb 05 '21 at 05:54
  • Sorry but I updated my question. Since the question is closed, can you or other people still see the question? @MadPhysicist – Yinda Yin Feb 05 '21 at 08:48
  • @YindaYin. Why not just transpose your array? Index starts with fancy index, so that will come first. If you know that will happen, then transpose the result. I don't think that deserves a separate question. – Mad Physicist Feb 05 '21 at 09:00
  • @MadPhysicist Yes that's true. Just as the duplicated question said: "This is easy to fix as part of my program, but it completely ruined my belief." I'm just trying to find a general way (if any) so that I do not need to worry about the indexing issues when I combine both fancy and basic indexing. – Yinda Yin Feb 05 '21 at 09:26
  • The general way is that if a fancy index comes first, the broadcasted dimensions of the fancy indices will come first. If the slice comes first, that gets used first. I'm not sure what answer you expect besides "watch what you're doing carefully". – Mad Physicist Feb 05 '21 at 09:53

0 Answers0