目录

数值范围中的数组(Array From Numerical Ranges)

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

如前所述,ndarray对象中的项遵循从零开始的索引。 有三种类型的索引方法可用 - field access, basic slicingadvanced indexing

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

例子1 (Example 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 (Example 2)

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

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

[2  4  6]

如果只放置一个参数,则将返回与索引对应的单个项目。 如果在其前面插入:,则将提取该索引以后的所有项目。 如果使用两个参数(在它们之间使用:),则会对具有默认第一步的两个索引(不包括停止索引)之间的项进行切片。

例子3 (Example 3)

# slice single item 
import numpy as np 
a = np.arange(10) 
b = a[5] 
print b

其输出如下 -

5

例子4 (Example 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]] 
↑回到顶部↑
WIKI教程 @2018