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
1 Answer
Reset to default 2As described in the advanced indexing section of the documentation:
When there is at least one slice (
:
), ellipsis (...
) ornewaxis
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 notx[arr1, :, 1]
since1
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
版权声明:本文标题:unexpected results when using normal and advanced indexing with numpy - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744662010a2618300.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论