(2)数组的索引、切片和历遍

对于一维数组,其索引、切片和历遍操作与Python列表中的相应操作基本一致。

import numpy as np

a = np.arange(10)**3

a
Out[74]: array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729], dtype=int32)

a[2]
Out[75]: 8

a[2:5]
Out[76]: array([ 8, 27, 64], dtype=int32)

a[:6:2] = -1000

a
Out[78]: array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729], dtype=int32)

a[::-1]
Out[79]: array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000], dtype=int32)

对于多维数组,每一个维度上均需给出一个索引值,不同维度的索引值之间用逗号隔开。

def f(x, y):
    return 10*x + y

b = np.fromfunction(f, (5,4), dtype=int)

b
Out[82]: 
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])

b[2,3]
Out[83]: 23

b[0:5,1]
Out[84]: array([ 1, 11, 21, 31, 41])

b[:,1]
Out[85]: array([ 1, 11, 21, 31, 41])

b[1:3,:]
Out[86]: 
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])

b[b[:,0]<20,1]
Out[89]: array([ 1, 11])

对于多维数组,如果给出的索引值数量少于数组的维度,则默认缺失索引值的维度上选取整个切片,如b[-1]等同于b[-1, :]b[i, ...]。注意,... 会根据数组的维度,自动省略对相应维度上索引值的定义。例如对于一个五维数组x

  • x[1, 2, ...]等价于x[1, 2, :, :, :]
  • x[..., 3]等价于x[:, :, :, :, 3]
  • x[4, ..., 5, :]等价于x[4, :, :, 5, :]
c = np.array([[[ 0, 1, 2], 
               [ 10, 12, 13]],
              [[100,101,102], 
               [110,112,113]]])

c.shape
Out[92]: (2, 2, 3)

c[1, ...]
Out[93]: 
array([[100, 101, 102],
       [110, 112, 113]])

c[..., 2]
Out[94]: 
array([[  2,  13],
       [102, 113]])

多维数组的历遍是相对于第一维进行的。如果要对数组中的每个元素进行历遍,可以使用数组的flat属性。

b
Out[95]: 
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])

for row in b:
    print(row)
    
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]

for element in b.flat:
    print(element)
    
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43

你可能感兴趣的:((2)数组的索引、切片和历遍)