## 二维矩阵的取法

In [1]: import numpy as npIn [2]: x = np.arange(16).reshape((4,4))In [3]: xOut[3]: array([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11],       [12, 13, 14, 15]])

## 取单行和单个元素

In [4]: id = 0In [5]: x[id]Out[5]: array([0, 1, 2, 3])In [6]: x[id][id]Out[6]: 0In [7]: x[id,id]Out[7]: 0

## 下标的list和tuple格式区分

In [8]: id = [1,1]In [9]: x[id]Out[9]: array([[4, 5, 6, 7],       [4, 5, 6, 7]])In [10]: x[id,id]Out[10]: array([5, 5])In [11]: id = (1,1)In [12]: x[id]Out[12]: 5

## 冒号的使用

In [14]: id = 1In [15]: x[id,:]Out[15]: array([4, 5, 6, 7])In [16]: x[:,id]Out[16]: array([ 1,  5,  9, 13])

## 现存的list与numpy.array不相兼容的取法

In [17]: id = [[1],[1]]In [18]: x[id]<ipython-input-18-23f8764f4b7e>:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.  x[id]Out[18]: array([5])In [19]: id = np.array([[1],[1]])In [20]: x[id]Out[20]: array([[[4, 5, 6, 7]],       [[4, 5, 6, 7]]])

## 两个冒号的组合用法

In [31]: x[::-1]Out[31]: array([[12, 13, 14, 15],       [ 8,  9, 10, 11],       [ 4,  5,  6,  7],       [ 0,  1,  2,  3]])In [32]: x[::-1,::-1]Out[32]: array([[15, 14, 13, 12],       [11, 10,  9,  8],       [ 7,  6,  5,  4],       [ 3,  2,  1,  0]])

## 用None作扩维

In [33]: x[None,:]Out[33]: array([[[ 0,  1,  2,  3],        [ 4,  5,  6,  7],        [ 8,  9, 10, 11],        [12, 13, 14, 15]]])In [34]: x[:,None,:]Out[34]: array([[[ 0,  1,  2,  3]],       [[ 4,  5,  6,  7]],       [[ 8,  9, 10, 11]],       [[12, 13, 14, 15]]])In [35]: x[:,:,None]Out[35]: array([[[ 0],        [ 1],        [ 2],        [ 3]],       [[ 4],        [ 5],        [ 6],        [ 7]],       [[ 8],        [ 9],        [10],        [11]],       [[12],        [13],        [14],        [15]]])

## 高维矩阵的取法

In [49]: y = np.arange(32).reshape((2,4,4))In [50]: yOut[50]: 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 [58]: id = np.array([[0,1],[2,3]])In [59]: y[np.arange(id.shape[0]),id[:,0],id[:,1]]Out[59]: array([ 1, 27])