numpy高级索引

时间:2022-04-12 17:38:37

布尔值索引

name_arr = np.array(["bob","joe","will","bob","joe","will","joe"])
rnd_arr = np_random.randn(7,4)
print(rnd_arr)
print(name_arr == "bob") #[ True False False True False False False]
print(rnd_arr[name_arr == "bob",2]) #[-0.39080416 0.39002854] 根据布尔值进行索引
mask_arr = (name_arr == 'bob') | (name_arr == 'will')
print(mask_arr)#[ True False True True False True False]
print(rnd_arr[mask_arr])

整数数组索引

用数组索引可以索引多个行或者多个列

for i in range(8):
arr[i] = i
# print(arr)
# print(arr[[4,3,0,6]])
# print(arr[[-3,-5,-7]])
arr = np.arange(32).reshape((8, 4))
print(arr)
print(arr[[1, 5, 7, 2], [0, 3, 1, 2]]) # 打印arr[1, 0]、arr[5, 3],arr[7, 1]和arr[2, 2]
print(arr[[1, 5, 7, 2]][:, [0, 3, 1, 2]]) # 1572行的0312列
print(arr[np.ix_([1, 5, 7, 2], [0, 3, 1, 2])]) # 可读性更好的写法

数组转换

#--------数组转换
arr = np.arange(15).reshape((3,5))
print(arr)
print(arr.T)
print(np.dot(arr,arr.T)) #矩阵乘法 #高维数组转换
a = np.arange(16).reshape((2,2,4))
#根据维度转换
# tanspose 维度本是0,1,2,3顺序往下排,我们可用transpose改变顺序
# 例如2,2,4 变为 4,2,2
print(a)
print(a.shape)
print(a.transpose((2,0,1)))
print(a.transpose((2,0,1)).shape)