1.3.1 索引¶
- 单个元素索引:一维数组、负数索引
- 二维数组的索引
1.3.2 切片¶
- 切片
- 跨步
- 索引数组: 针对多为数组的索引
- 索引结合切片
import numpy as npIn [2]:
# 一维数组索引 array1 = np.array([1,2,3,4,5]) array1Out[2]:
array([1, 2, 3, 4, 5])In [3]:
# 取第4个数值 array1[3]Out[3]:
4In [5]:
array1[-2] # 倒数第2个数字Out[5]:
4In [6]:
# 二维数组 array2 = np.arange(14).reshape(2,7) array2Out[6]:
array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13]])In [7]:
# 第一行第三列数字 array2[0,3]Out[7]:
3In [8]:
array2[0][3]Out[8]:
3In [9]:
array2[-1,-1]Out[9]:
13In [10]:
array2[0,-1]Out[10]:
6In [11]:
# 三维数组 array3 = np.arange(30).reshape(2,3,5) array3Out[11]:
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, 24], [25, 26, 27, 28, 29]]])In [12]:
array3[0,1,2]Out[12]:
7In [13]:
# 切片 array1Out[13]:
array([1, 2, 3, 4, 5])In [15]:
array1[0:3] # a~b,a<=x<bOut[15]:
array([1, 2, 3])In [16]:
array1[2:6]Out[16]:
array([3, 4, 5])In [17]:
array1[2:]Out[17]:
array([3, 4, 5])In [20]:
array1[:-1]Out[20]:
array([1, 2, 3, 4])In [21]:
# 二维数组的切片 array2Out[21]:
array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13]])In [36]:
array2[0:1,:] # 行参数、列参数Out[36]:
array([[0, 1, 2, 3, 4, 5, 6]])In [26]:
array2[1:,:] # 行参数、列参数Out[26]:
array([[ 7, 8, 9, 10, 11, 12, 13]])In [28]:
array2[:,3:4]Out[28]:
array([[ 3], [10]])In [29]:
array2[0:,3:4]Out[29]:
array([[ 3], [10]])In [30]:
array2[1:,3:4]Out[30]:
array([[10]])In [35]:
array2[0:1,3:4]Out[35]:
array([[3]])In [32]:
# 三维数组 array3Out[32]:
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, 24], [25, 26, 27, 28, 29]]])In [33]:
array3[0:1,2:,:]Out[33]:
array([[[10, 11, 12, 13, 14]]])In [34]:
array3[0:1,2:,:][0,0,2]Out[34]:
12In [37]:
# 索引多个数值 array1Out[37]:
array([1, 2, 3, 4, 5])In [38]:
array1[np.array([0,2,4])] # 获取第1位,第3位,第5位的数值Out[38]:
array([1, 3, 5])In [39]:
# 二维数组 array2Out[39]:
array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13]])In [40]:
array2[np.array([0,1]),np.array([1,2])] # 获取第1行第2列,第2行第3列数字Out[40]:
array([1, 9])In [ ]: 标签:10,12,array2,array1,基本操作,array,numpy,Out From: https://www.cnblogs.com/mlzxdzl/p/17767808.html