python中numpy矩陣的切片操作slicing心得
>>> d = np.array(c)
>>> d
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9],
[11, 12, 13, 14, 15, 16, 17, 18, 19],
[21, 22, 23, 24, 25, 26, 27, 28, 29],
[31, 32, 33, 34, 35, 36, 37, 38, 39],
[41, 42, 43, 44, 45, 46, 47, 48, 49]])
>>> d[1,4]
15
切出一個列
>>> d[:,1]
array([ 2, 12, 22, 32, 42])
切出多個列
>>> d[:,1:3]
array([[ 2, 3],
[12, 13],
[22, 23],
[32, 33],
[42, 43]])
>>> d[:,1:4]
array([[ 2, 3, 4],
[12, 13, 14],
[22, 23, 24],
[32, 33, 34],
[42, 43, 44]])
切出帶步長的多個列>>> d[:,1:4:2]
array([[ 2, 4],
[12, 14],
[22, 24],
[32, 34],
[42, 44]])
由上可看出,與普通list的切片操作(起始:終止:步長)不同的是,在第二個引數“終止”可以用“,1”的形式表達只對列進行切片操作,其後的下一個“:”則表達對列的另一個切片(起始:終止),再之後的冒號才是步長的引數。例如d[:,1:4:2]表達的是對第1到第4-1,也就是第1-3列進行步長為2的切片操作.
d[行起始:行終止,列起始:列終止:步長]