ndarray的索引和切片¶
整数索引和切片索引
In [58]:
arr = np.arange(8)
arr
Out[58]:
array([0, 1, 2, 3, 4, 5, 6, 7])
In [59]:
arr[5] # 下标为5
Out[59]:
5
In [61]:
arr[1:4] # 同时获取索引为1,2,3的值
Out[61]:
array([1, 2, 3])
In [63]:
arr[1:6:2] # 获取索引为1-5的值,步长为2,隔一个取一个
Out[63]:
array([1, 3, 5])
二维数组对象切片
In [64]:
arr2d = np.arange(1,10).reshape(3,3)
arr2d
Out[64]:
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
In [65]:
arr2d[1] # 获取行索引为1的行
Out[65]:
array([4, 5, 6])
In [67]:
arr2d[0,1] # 获取行索引为0,列索引为1的值
Out[67]:
2
In [69]:
arr2d[:2] # 切出第一行和第二行
Out[69]:
array([[1, 2, 3], [4, 5, 6]])
In [71]:
arr2d[0:2,0:2]
Out[71]:
array([[1, 2], [4, 5]])
In [70]:
arr2d = np.arange(1,10).reshape(3,3)
arr2d
Out[70]:
array([[1, 2, 3], [4, 5, 6], [7, 8