且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在3D数组上同时使用切片索引和布尔索引时的结果很奇怪

更新时间:2022-11-25 17:27:14

a[0, :, mask]将高级索引与切片混合在一起. :是切片索引",而0(为此)和mask被认为是高级索引".

a[0, :, mask] mixes advanced indexing with slicing. The : is a "slice index", while the 0 (for this purpose) and mask are consider "advanced indexes".

规则控制高级索引和切片同时处于组合状态时的索引行为:

The rules governing the behavior of indexing when both advanced indexing and slicing are combined state:

索引操作分为两部分,基本索引定义的子空间(不包括整数)和高级索引部分的子空间.需要区分索引组合的两种情况:

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:

  • 高级索引用切片,省略号或换轴符分隔.例如x[arr1, :, arr2].
  • 高级索引是彼此相邻.例如,x[..., arr1, arr2, :]但不是x[arr1, :, 1],因为1在这方面是高级索引.
    • 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[0, :, mask]具有由切片分隔的高级索引(第一种情况),结果数组的形状具有与高级索引相关联的轴被推到前面,而与切片相关的轴则被推到末端.因此,形状为(3, 2),因为mask与长度3的轴关联,而切片:与长度2的轴关联.(实际上,0索引删除了长度的轴1从结果数组中移出,因此它在结果形状中不起作用.)

      So since a[0, :, mask] has advanced indexes separated by a slice (the first case), the shape of the resulting array has the axes associated to the advanced indexes pushed to the front and the axes associated with the slice pushed tho the end. Thus the shape is (3, 2) since the mask is associated with the axis of length 3, and the slice, :, associated with the axis of length 2. (The 0 index in effect removes the axis of length 1 from the resultant array so it plays no role in the resultant shape.)

      相反,b[:, mask]将所有高级索引放在一起(第二种情况).因此,所得数组的形状使轴保持在原位.因此b[:, mask].shape(2, 3).

      In contrast, b[:, mask] has all the advanced indexes together (the second case). So the shape of the resulting array keeps the axes in place. b[:, mask].shape is thus (2, 3).