numpy基础属性方法随机整理(二)---切片 slice

注意:
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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值