運行以下代碼:
3 import numpy as np
4
5 aa = np.array([
6 [1,2,3,4],
7 [5,6,7,8],
8 [9,8,7,6]
9 ])
10
11 r1 = aa[2,:]
12 r2 = aa[2:3,:]
13
14 print r1.shape , r1
15 print r2.shape , r2
16
17 r3 =np.array([[1],[2],[3],[4]])
18
19 print r3.shape
輸出結果是:
(4,) [9 8 7 6]
(1, 4) [[9 8 7 6]]
(4, 1)
r3 與 r1的區別在於 r1 只有一個維度,[9 8 7 6]
r1 = aa[2,:] ,第一維度用了整數索引,第二維度用了切片索引,用整數索引表示直接取值即可,所以只剩下1個維度
r2 = aa[2:3,:] 兩個維度都用了切片索引,所以得到的數組還是2維的。
剛剛學習numpy , 有不對的地方還請大神指點。