numpy 數組索引
一、單個元素索引
一維數組索引
>>> x = np.arange(10) >>> x[2] 2 >>> x[-2] 8
二維數組索引
>>> x.shape = (2,5) # now x is 2-dimensional >>> x[1,3] 8 >>> x[1,-1] 9
數組切片
>>> x = np.arange(10)
>>> x[2:5]
array([2, 3, 4])
>>> x[:-7]
array([0, 1, 2])
>>> x[1:7:2]
array([1, 3, 5])
>>> y = np.arange(35).reshape(5,7)
>>> y[1:5:2,::3]
array([[ 7, 10, 13],
[21, 24, 27]])
二、使用數組索引數組
例:產生一個一組數組,使用數組來索引出需要的元素。讓數組[3,3,1,8]取出x中的第3,3,1,8的四個元素組成一個數組view
>>> x = np.arange(10,1,-1) >>> x array([10, 9, 8, 7, 6, 5, 4, 3, 2]) >>> x[np.array([3, 3, 1, 8])] array([7, 7, 9, 2])
當然,類似切片那樣,Index也可以使用負數。但是索引值不能越界!
>>> x[np.array([3,3,-3,8])] array([7, 7, 4, 2])
三、索引多維數組
例1:產生一個5X7的數組,選擇0,2,4行,0,1,2列的數
>>> y = np.arange(35).reshape(5,7) >>> y[np.array([0,2,4]), np.array([0,1,2])] array([ 0, 15, 30])
例2:選取第0,2,4行,第1列的值
>>> y[np.array([0,2,4]), 1] array([ 1, 15, 29])
例3:選取第0,2,4行的值
>>> y[np.array([0,2,4])]
array([[ 0, 1, 2, 3, 4, 5, 6],
[14, 15, 16, 17, 18, 19, 20],
[28, 29, 30, 31, 32, 33, 34]])
四、布爾值或掩碼索引數組
例1
>>> y = np.arange(35) >>> b = y>20 >>> y[b] array([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34])
例2
>>> b[:,5] # use a 1-D boolean whose first dim agrees with the first dim of y
array([False, False, False, True, True], dtype=bool)
>>> y[b[:,5]]
array([[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34]])
例3
>>> x = np.arange(30).reshape(2,3,5)
>>> x
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]]])
>>> b = np.array([[True, True, False], [False, True, True]])
>>> x[b]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])
五、數組與切片的組合索引數組
例1:產生一個5X7的數組,使用數組來索引第一個軸,使用切換來索引第二個軸
>>> y = np.arange(35).reshape(5,7)
>>> y[np.array([0,2,4]),1:3]
array([[ 1, 2],
[15, 16],
[29, 30]])
例2:切片與布爾類型索引
>>> y[b[:,5],1:3]
array([[22, 23],
[29, 30]])
六、Structural indexing tools
例1:使用np.newwaxis可以直接擴展維度
>>> y.shape (5, 7) >>> y[:,np.newaxis,:].shape (5, 1, 7)
例2:這是利用了擴展維度與廣播特性的矩陣相加。用5X1矩陣與1X5矩陣相加。
>>> x = np.arange(5)
>>> x[:,np.newaxis] + x[np.newaxis,:]
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
例3:使用 ... 符號來表示其他維度
>>> z = np.arange(81).reshape(3,3,3,3)
>>> z[1,...,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])
這例子也相當於下面的代碼實現
>>> z[1,:,:,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])
另有:https://docs.scipy.org/doc/numpy/user/quickstart.html#fancy-indexing-and-index-tricks
