numpy——索引和切片
程序员文章站
2023-11-10 10:03:04
t1=np.arange(24).reshape((4,6))t1Out[3]: 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]])取t1第二行:t1[1]Out[4]: array([ 6, 7, 8, 9, 10, 11])2.取连续的多行t1[1:]Out[5]...
t1=np.arange(24).reshape((4,6))
t1
Out[3]:
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]])
取t1第二行:
t1[1] Out[4]: array([ 6, 7, 8, 9, 10, 11])
2.取连续的多行
t1[1:] Out[5]:
array([[ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
3.取不连续的多行:
#取不连续的多行,取1,3,4行 t1[[0,2,3]] Out[8]:
array([[ 0, 1, 2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
4.更为通用的写法:
不管取行还是取列,通用t1[,],左边为取行右边为取列,如果左右放冒号说明我们每行都要或者每列都要
比如说:
#取第二行 t1[1,:] Out[12]: array([ 6, 7, 8, 9, 10, 11])
#取1,3,4行 t1[[0,2,3],:] Out[15]:
array([[ 0, 1, 2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
4.取n行n列
#取2行3列 t1[2,3] Out[23]: 15
第二行到第4行,第二列到第4列
注意此处从[1:3]只能取到2行到3列,取不到第四列
#取第二行到第4行,第二列到第4列 t1[1:3,1:3] Out[25]:
array([[ 7, 8], [13, 14]])
正确的应该是:
t1
Out[26]:
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]]) t1[1:4,1:4] Out[27]:
array([[ 7, 8, 9], [13, 14, 15], [19, 20, 21]])
5.取多个不相邻的点
#取多个不相邻的点 t1[[0,1,1],[1,2,5]] Out[32]: array([ 1, 8, 11])
选出来的结果为位置(0,1)(1,2)(1,5)的点
本文地址:https://blog.csdn.net/zhangqiqiyihao/article/details/109024958