Python numpy 数组负索引

Python numpy array negative indexing

我对 numpy 的索引有点困惑。假设以下示例:

>>> import numpy as np
>>> x = np.arange(10)
>>> x.shape = (2,5)
>>> x
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> x[0:-1]
array([[0, 1, 2, 3, 4]])
>>> x[1:-1]
array([], shape=(0, 5), dtype=int64)
>>> x[1:]
array([[5, 6, 7, 8, 9]])

让我感到困惑的是,我可以使用 x[0:-1] 将第一行作为二维数组获取。但是 -1 在索引方面实际上意味着什么?我本以为,调用 x[1:-1] 会给我第二行,但是如果 returns 我是一个空数组,为了得到我想要的,我需要使用 x[1:]?

我有点困惑。 感谢帮助

你有这个声明:

In [31]: x[0:-1]

这种索引方式就是"start at 1st row and go till the last row (excluded)"。这就是我们得到第一行结果的原因。

Out[31]: array([[0, 1, 2, 3, 4]])

但是,当你这样做时:

 In [31]: x[1:-1]   
 Out[31]: array([], shape=(0, 5), dtype=int64)

它要求 NumPy "start at second row and not include the last row"。由于此处第二行也是最后一行,因此将其排除在外,结果我们得到一个空数组。


更多信息:这里没有关于使用诸如 -1 之类的负索引的具体说明。例如,以下索引方式也会 return 空数组。

# asking to "start at first row and end at first row"
In [42]: x[0:0]  
Out[42]: array([], shape=(0, 5), dtype=int64)

# asking to "start at second row and end at second row"
In [43]: x[1:1]  
Out[43]: array([], shape=(0, 5), dtype=int64)

Python/NumPy中的索引总是“左包含右独占”。

这是简单的 Python(即索引 list

In [52]: lst = [1, 2] 

In [53]: lst[1:-1]    
Out[53]: []   # an empty list

请注意索引的构造是:[start:stop:step]

如果我们 startstop 在同一个索引处,那么我们将无处可去,并且数据结构为空(array/list/tuple等)结果 returned。

如果您请求切片 x[a:b],您将收到从 ab 的部分,但不包括 b。因此,如果您切片 x[1:-1],生成的数组将不包含 -1,这恰好与 (2,5) 数组中的 1 相同。另一个例子:

>>> import numpy as np
>>> x = np.arange(15)
>>> x.shape = (3,5)
>>> x
array([[0,  1,  2,  3,  4],
       [5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> x[0:-1]
array([[0, 1, 2, 3, 4]])
>>> x[1:-1]
array([[5, 6, 7, 8, 9]])

上面的最后一个操作切片 x 从行 1 到(不包括)最后一行,即行 1.