花式索引

花式索引和切片不一样,它总是将数据复制到新数组中。

整数数组进行索引:

In [60]: arr = np.empty((8, 4))
In [61]: for i in range(8):
    arr[i] = i
In [62]: arr
Out[62]:
array([[ 0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.],
       [ 4.,  4.,  4.,  4.],
       [ 5.,  5.,  5.,  5.],
       [ 6.,  6.,  6.,  6.],
       [ 7.,  7.,  7.,  7.]])
In [63]: arr[[3, 2, 1, -8]]  # 负数索引将从行末开始选行
Out[63]:
array([[ 3.,  3.,  3.,  3.],
       [ 2.,  2.,  2.,  2.],
       [ 1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.]])

一次传入多个索引数组会返回一个一维数组:

In [68]: arr = np.arange(32).reshape((8, 4))
In [69]: arr
Out[69]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23],
       [24, 25, 26, 27],
       [28, 29, 30, 31]])
In[70]: arr[[1, 5, 7, 2], [0, 3, 1, 2]]
Out[70]: array([ 4, 23, 29, 10])

选取矩阵的行列子集:

In [75]: arr[[1, 5, 7, 2]][:, [0, 3, 1, 2]]
Out[75]:
array([[ 4,  7,  5,  6],
       [20, 23, 21, 22],
       [28, 31, 29, 30],
       [ 8, 11,  9, 10]])
In [76]: arr[np.ix_([1, 5, 7, 2], [0, 3, 1, 2])]
Out[76]:
array([[ 4,  7,  5,  6],
       [20, 23, 21, 22],
       [28, 31, 29, 30],
       [ 8, 11,  9, 10]])

数组转置和轴对换

转置(transpose)是重塑的一种特殊形式,它将返回的源数据视图(不会进行复制操作)

T属性:

In [77]: arr = np.arange(15).reshape((3, 5))

In [78]: arr
Out[78]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [79]: arr.T
Out[79]:
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])