📜  NumPy-索引和切片

📅  最后修改于: 2020-11-08 07:35:29             🧑  作者: Mango


可以通过索引或切片来访问和修改ndarray对象的内容,就像Python的内置容器对象一样。

如前所述,ndarray对象中的项遵循从零开始的索引。提供三种类型的索引编制方法-字段访问,基本切片高级索引编制。

基本切片是Python基本切片概念的扩展。通过向内置slice函数提供start,stopstep参数来构造Python slice对象。将此切片对象传递到数组以提取数组的一部分。

例子1

import numpy as np 
a = np.arange(10) 
s = slice(2,7,2) 
print a[s]

其输出如下-

[2  4  6]

在上面的示例中, ndarray对象是通过arange ()函数准备的。然后,分别以开始,停止和步进值2、7和2定义切片对象。当将此切片对象传递给ndarray时,将对其中一部分从索引2到7到步骤2进行切片。

通过将以冒号:(start:stop:step)分隔的切片参数直接提供给ndarray对象,也可以获得相同的结果。

例子2

import numpy as np 
a = np.arange(10) 
b = a[2:7:2] 
print b

在这里,我们将获得相同的输出-

[2  4  6]

如果仅输入一个参数,则将返回与索引相对应的单个项目。如果在其前面插入:,将从该索引开始的所有项目都将被提取。如果使用两个参数(在它们之间带有:),则将对两个索引之间的项(不包括停止索引)进行切片(默认为第一步)。

例子3

# slice single item 
import numpy as np 

a = np.arange(10) 
b = a[5] 
print b

其输出如下-

5

例子4

# slice items starting from index 
import numpy as np 
a = np.arange(10) 
print a[2:]

现在,输出将是-

[2  3  4  5  6  7  8  9]

例子5

# slice items between indexes 
import numpy as np 
a = np.arange(10) 
print a[2:5]

在这里,输出将是-

[2  3  4] 

上面的描述也适用于多维ndarray

例子6

import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print a  

# slice items starting from index
print 'Now we will slice the array from the index a[1:]' 
print a[1:]

输出如下-

[[1 2 3]
 [3 4 5]
 [4 5 6]]

Now we will slice the array from the index a[1:]
[[3 4 5]
 [4 5 6]]

切片还可以包括省略号(…),以使选择元组的长度与数组的维数相同。如果在行位置使用省略号,它将返回由行中的项组成的ndarray。

例子7

# array to begin with 
import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 

print 'Our array is:' 
print a 
print '\n'  

# this returns array of items in the second column 
print 'The items in the second column are:'  
print a[...,1] 
print '\n'  

# Now we will slice all items from the second row 
print 'The items in the second row are:' 
print a[1,...] 
print '\n'  

# Now we will slice all items from column 1 onwards 
print 'The items column 1 onwards are:' 
print a[...,1:]

该程序的输出如下-

Our array is:
[[1 2 3]
 [3 4 5]
 [4 5 6]] 
 
The items in the second column are: 
[2 4 5] 

The items in the second row are:
[3 4 5]

The items column 1 onwards are:
[[2 3]
 [4 5]
 [5 6]]