数组的索引和切片
一维数组的索引和切片:
In [48]: a=np.array([9,8,7,6,5])
In [49]: a[2]
Out[49]: 7
In [50]: a[1:4:2]
Out[50]: array([8, 6])
多维数组的索引:
每个维度一个索引值,逗号分割
In [43]: a=np.arange(24).reshape((2,3,4))
In [44]: a
Out[44]:
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]]])
In [45]: a[1,2,3]
Out[45]: 23
In [46]: a[0,1,2]
Out[46]: 6
In [47]: a[-1,-2,-3] #每个维度一个索引值,逗号分割
Out[47]: 17
多维数组的切片:
In [54]: a=np.arange(24).reshape((2,3,4))
In [55]: a[:,1,-3] #选取一个维度用:
Out[55]: array([ 5, 17])
In [56]: a[:,1:3,:] #每个维度切片方法与一维数组相同
Out[56]:
array([[[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
In [57]: a[:,:,::2] #每个维度可以使用步长跳跃切片
Out[57]:
array([[[ 0, 2],
[ 4, 6],
[ 8, 10]],
[[12, 14],
[16, 18],
[20, 22]]])