一、切片与索引基础
import numpy as np #1.一维数组切片 arr1=np.arange(10) s=slice(2,7,2)#2到7每次增加2 print(arr1[s])#其等价于--> print(arr1[2:7:3]) print(arr1[2:-1:1])#2到最后一个但是不包含最后一个 print(arr1[4])#4 print(arr1[0])#0 print(arr1[:])#全部 print(arr1[2:-1]," ---------------")#2开始到最后一个但是不包含最后一个 #2.二维数组切片 arr2=np.arange(20) arr2.shape=(4,5) print(arr2) print(arr2[0])#取出二维数组中的第一个一维数组 print(arr2[2][1:3])#第三个数组从一到三不包括三 print(arr2[::2]," ---------------")#步长为2 print(arr2[1,...])#取出第二行 print(arr2[...,1])#取出第二列 print(arr2[1:3,...])#取出一 到三行 print(arr2[...,1:3])#取出一到二列
二、高级索引
import numpy as np #1.例子 myarray=np.arange(9) myarray.shape=(3,3) mydata=myarray[[0,1,2],[0,1,2]]#[0 4 8] 00 11 22 xy坐标 mydata=myarray[[0,1,2],[2,1,0]]#[2 4 6] 02 11 20 xy坐标 #2.深入 myarray2=np.arange(12) myarray2.shape=(4,3) rows=np.array([[0,0],[3,2]]) cols=np.array([[0,2],[2,0]]) print(myarray2," -------------") #[[ 0 1 2] # [ 3 4 5] # [ 6 7 8] # [ 9 10 11]] print(rows," -------------") #[[0 0] 0 # [3 2]] 11 print(cols," -------------") #[[0 2] 2 # [2 0]] 6 print(myarray2[rows,cols]," -------------")#矩阵的乘法 #3.联合挖掘 print(myarray2[1:3,1:3]," -------------")#行1-3,列1-3 不包括3 #[[4 5] # [7 8]] print(myarray2[1:3,[1,2]]," -------------")#行1-3,第一列和第二列 print(myarray2[1:3,[0,1,2]]) #[[3 4 5] # [6 7 8]]