代码之家  ›  专栏  ›  技术社区  ›  fountainhead

带切片与范围的数据数组索引结果的维数

  •  1
  • fountainhead  · 技术社区  · 6 年前

    我试图理解 range 作为索引,并将其与使用切片作为索引进行比较 ndarray . 具体来说,对结果维度的影响。

    我理解的是:

    1. 对于 恩达雷 ,如果使用标量索引(如2),结果的维数将小于原始的维数。 恩达雷 ,1。

    2. 如果我使用 slice(2,3) 不会发生上述维度的缩减。

    在大多数情况下,如果我使用 范围 而不是 slice 对维度的影响似乎是相同的,但对于一个特殊的情况。

    这是密码。对我来说,惊喜出现在第四份印刷声明中:

    import numpy as np
    
    nd15 = np.array([['e00','e01','e02','e03'],
                     ['e10','e11','e12','e13'], 
                     ['e20','e21','e22','e23']])
    
    # Consider the dimensionality of the indexing results from the below 4 
    # lines.
    # From the first 3 print statements, we are led to believe that, if you
    # replace a range with an "equivalent" slice-expression, the
    # dimensionality of the result will remain unchanged.
    # But the fourth result below surprisingly negates that understanding.
    print (nd15[slice(2,3), slice(2,3)].shape)
    print (nd15[slice(2,3), range(2,3)].shape)
    print (nd15[range(2,3), slice(2,3)].shape)
    print (nd15[range(2,3), range(2,3)].shape)
    

    我希望第四版也能得到和其他三版一样的结果。

    相反,这是我得到的结果:

    (1, 1)
    (1, 1)
    (1, 1)
    (1,)
    

    我错过了什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Mad Physicist    6 年前

    你触发了两种不同类型的 advanced indexing 但由于 range ndarray .

    当你拥有 范围 list 在这两个索引中,您将触发 integer array indexing . 在这个方案中,结果将与广播索引数组的形状相同。在本例中,这是一个一维数组,因为这就是范围转换的目的。

    当一个索引是可重索引,另一个是切片时,您将触发 a form of hybrid indexing . 在这种情况下,形状具有来自高级索引(1)和切片(1)的维度组合。如果指定了二维嵌套列表而不是 范围 对于高级索引,您将获得一个3D输出。

        2
  •  0
  •   hpaulj    6 年前

    切片和范围表达式也可以写成:

    In [86]: nd15[2:3, 2:3]
    Out[86]: array([['e22']], dtype='<U3')
    In [87]: nd15[2:3, [2]]
    Out[87]: array([['e22']], dtype='<U3')
    In [88]: nd15[[2],2:3]
    Out[88]: array([['e22']], dtype='<U3')
    In [89]: nd15[[2],[2]]
    Out[89]: array(['e22'], dtype='<U3')
    

    nd15[2,2] 将是标量元素“e22”。

    但是,如果我们扩展切片以生成(2,2)数组,差异可能会更明显:

    In [97]: nd15[1:3, 2:4]
    Out[97]: 
    array([['e12', 'e13'],
           ['e22', 'e23']], dtype='<U3')
    In [98]: nd15[1:3,[2,3]]
    Out[98]: 
    array([['e12', 'e13'],
           ['e22', 'e23']], dtype='<U3')
    In [99]: nd15[[1,2], 2:4]
    Out[99]: 
    array([['e12', 'e13'],
           ['e22', 'e23']], dtype='<U3')
    In [100]: nd15[[1,2], [2,3]]
    Out[100]: array(['e12', 'e23'], dtype='<U3')
    

    最后一个元素是对角线,即(1,2)和(2,3)元素。

    Out[86] Out[97] views ,其余为复印件。