admin管理员组

文章数量:1389754

Consider the following:

import numpy as np

a = np.random.rand(123, 45, 3)

print(a[:, :, [0, 1]].shape)  # (123, 45, 2)
print(a[:, 0, [0, 1]].shape)  # (123, 2)
print(a[0, :, [0, 1]].shape)  # (2, 45)

Why is the last array transposed?

Consider the following:

import numpy as np

a = np.random.rand(123, 45, 3)

print(a[:, :, [0, 1]].shape)  # (123, 45, 2)
print(a[:, 0, [0, 1]].shape)  # (123, 2)
print(a[0, :, [0, 1]].shape)  # (2, 45)

Why is the last array transposed?

Share Improve this question asked Mar 14 at 10:29 lebowskilebowski 1016 bronze badges 1
  • 1 Related: github/numpy/numpy/issues/21104 – 9769953 Commented Mar 14 at 10:36
Add a comment  | 

1 Answer 1

Reset to default 2

As described in the advanced indexing section of the documentation:

When there is at least one slice (:), ellipsis (...) or newaxis in the index (or the array has more dimensions than there are advanced indices), then the behaviour can be more complicated. It is like concatenating the indexing result for each advanced index element.

[...]

The easiest way to understand a combination of multiple advanced indices may be to think in terms of the resulting shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished:

The advanced indices are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].

The advanced indices are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing).

In your case a[:, 0, [0, 1]] is matching the second case (the original order of the dimensions is maintained), and a[0, :, [0, 1]] the first case (advanced indexing first).

You may use:

a[0][:, [0, 1]].shape   # (45, 2)

# or
a[..., [0, 1]][0].shape # (45, 2)

本文标签: unexpected results when using normal and advanced indexing with numpyStack Overflow