scipy Python numpy数组负索引

zwghvu4y  于 2022-11-10  发布在  Python
关注(0)|答案(2)|浏览(160)

I'm a bit confused about the indexing of numpy. Assume the following example:

>>> 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]])

What I'm confused about, I can get the first row as 2D-array using x[0:-1] . But what does the -1 actually means in terms of indices? I would have thought, that calling x[1:-1] would then give me the second row, but instead if returns me an empty array, and to get what I want I need to use x[1:]?
I'm a little bit confused. Thanks for the help

a9wyjsp7

a9wyjsp71#

你有这样的说法:

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

这种索引方式意味着“从第一行开始,直到最后一行(不包括)"。这就是为什么我们得到的结果是第一行。

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

但是,当您这样做时:

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

它要求NumPy“从第二行开始,不包括最后一行”。因为这里的第二行也是最后一行,所以它被排除,我们得到一个空数组。

更多信息:这里没有什么特别的关于使用诸如-1之类的负索引。例如,下面的索引方法也会返回空数组。


# 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 在同一个索引上,那么我们什么也得不到,并且返回一个空的数据结构(数组/列表/元组等)作为结果。

8yoxcaq7

8yoxcaq72#

如果请求切片x[a:b],则会收到从ab(但不包括b)的部分。因此,如果对x[1:-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],
       [5, 6, 7, 8, 9]])
>>> x[1:-1]
array([[5, 6, 7, 8, 9]])

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

相关问题