【问题标题】:Can someone explain this numpy slicing behaviour?有人可以解释这种 numpy 切片行为吗?
【发布时间】:2021-12-11 08:06:09
【问题描述】:

有人能解释一下为什么下面的第二个断言失败了吗?我不明白为什么在这种情况下使用切片或范围进行索引会有所不同。

import numpy as np

d = np.zeros(shape = (1,2,3))
assert d[:, 0, slice(0,2)].shape == d[:, 0, range(0,2)].shape #This doesn't trigger an exception as both operands return (1,2)
assert d[0, :, slice(0,2)].shape == d[0, :, range(0,2)].shape #This does because (1,2) != (2,1)...

【问题讨论】:

    标签: numpy slice


    【解决方案1】:

    使阵列更具诊断性:

    In [66]: d = np.arange(6).reshape(1,2,3)
    In [67]: d
    Out[67]: 
    array([[[0, 1, 2],
            [3, 4, 5]]])
    

    中间的标量索引:

    In [68]: d[:,0,:2]
    Out[68]: array([[0, 1]])
    In [69]: d[:,0,range(2)]
    Out[69]: array([[0, 1]])
    

    两者的形状都是 (1,2),尽管由于最后一个维度的高级索引,第二个是副本。

    第二组形状相同,但顺序实际上不同:

    In [70]: d[0,:,:2]
    Out[70]: 
    array([[0, 1],
           [3, 4]])
    In [71]: d[0,:,range(2)]
    Out[71]: 
    array([[0, 3],
           [1, 4]])
    

    [71] 是一个混合基本索引和高级索引的案例,它被记录为做意外。中间的切片维度放在最后。

    https://numpy.org/doc/stable/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多