具有条件转置维度的 numpy 索引
numpy indexing with conditional transposes dimensions
当我混合掩码索引和普通索引时,我得到了一个奇怪的结果:
a = np.zeros((3,2,5))
cond = [True]*5
print(a[0][:,cond].shape) # prints '(2,5)' as expected
print(a[0,:,cond].shape) # prints '(5,2)' which is surprising
也就是说,结果数组是从我认为应该发生的情况转置的
这是一个错误吗?这是一个功能吗?如果有人能给我指出一份解释这一点的文档,我将非常高兴:)
不,这不是错误。发生这种情况是因为您混合了基本索引(切片)和高级索引(整数和布尔数组)。已记录 here:
Two cases of index combination need to be distinguished:
The advanced indexes are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].
The advanced indexes 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).
当我混合掩码索引和普通索引时,我得到了一个奇怪的结果:
a = np.zeros((3,2,5))
cond = [True]*5
print(a[0][:,cond].shape) # prints '(2,5)' as expected
print(a[0,:,cond].shape) # prints '(5,2)' which is surprising
也就是说,结果数组是从我认为应该发生的情况转置的
这是一个错误吗?这是一个功能吗?如果有人能给我指出一份解释这一点的文档,我将非常高兴:)
不,这不是错误。发生这种情况是因为您混合了基本索引(切片)和高级索引(整数和布尔数组)。已记录 here:
Two cases of index combination need to be distinguished:
The advanced indexes are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].
The advanced indexes 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).