numpy基礎屬性方法隨機整理(二)---切片 slice
阿新 • • 發佈:2019-01-26
注意:
a[::-2] :切片起始索引和終止索引省略,-2表示逆序步長為2;
a[-4::-2] :起始索引逆序第4個,終止索引為0,逆序步長為2;
a[2::3] :起始索引為2,終止索引為最後一個,正序步長為3;
b[…,1] D0和D1不作約束,D2切片index=1的資料
注:{axis=0:’D0’,axis=1:’D1’, axis=2:’D2’ }
切片code如下:
一維陣列:
import os
import sys
import numpy as np
def main (argc, argv, envp):
a = np.arange(1,20 ,2)
print('shape:', a.shape) # (10,) a:[ 1 3 5 7 9 11 13 15 17 19]
print('1):',a[:3]) # 索引0,1,2
print('2):', a[1:6]) # 索引1~5,不包含索引6
print('3):', a[5:]) # 索引5及其之後的所有索引
print('4):', a[:-3]) # 索引0~索引6(逆序第3個索引之前的索引)
print('5):' , a[::-1]) # 所有索引逆序,起始和終止索引省略表示,-1表示逆序步長為1
print('6):', a[::-2]) # 所有索引逆序,起始和終止索引省略表示,-2表示逆序步長為2
return 0
if __name__ == '__main__':
sys.exit(main(len(sys.argv), sys.argv, os.environ))
output:
shape: (10,)
1): [1 3 5]
2): [ 3 5 7 9 11]
3): [11 13 15 17 19]
4): [ 1 3 5 7 9 11 13]
5): [19 17 15 13 11 9 7 5 3 1]
6): [19 15 11 7 3]
[Finished in 1.4s]
多維陣列:
import os
import sys
import numpy as np
def main (argc, argv, envp):
b = np.arange(1,25).reshape(2,3,4)
print('b:','\n',b,'\n') # {axis=0:'D0',axis=1:'D1', axis=2:'D2'}
print('1)', b[:,0,0],'\n') # D0不做約束,D1和D2切片index=0的資料
print('2)', b[0,:,:],'\n') # 切片D0中index=0的資料,D1和D2不作約束
print('3)', b[...,1],'\n') # D0和D1不作約束,D2切片index=1的資料
print('4)', b[0,1,::2],'\n') # 切片D0 index=0,D1 index=1,D2中起始到終止的正序步長2的資料
print('5)', b[:,1],'\n') # D0和D2不作約束,切片D1 index=1的資料
print('=5)', b[:,1,:],'\n') # D0和D2不作約束,切片D1 index=1的資料
return 0
if __name__ == '__main__':
sys.exit(main(len(sys.argv), sys.argv, os.environ))
- output:
b:
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
1) [ 1 13]
2) [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
3) [[ 2 6 10]
[14 18 22]]
4) [5 7]
5) [[ 5 6 7 8]
[17 18 19 20]]
=5) [[ 5 6 7 8]
[17 18 19 20]]
[Finished in 1.4s]