numpy 对矩阵对角线、上三角、下三角以及它们所在位置索引的提取
import numpy as np a = np.random.randint(0,10,[5,5]) print(a) # c = np.triu(a,0) #上三角 # print(c) # d = np.tril(a,0) # 下三角 # print(d) # 寻找上三角形的位置 up = np.triu(a,1) up_bool = a==up up_palce = np.argwhere(up_bool==True) for i,j in up_palce: if i<=j: # 下三角就是x大于等于y,他两想相反。 a[i,j] = 66 print(a) # 寻找对角线的位置 c = np.diag(a,0) print(c) s = a==c index = np.argwhere(s==True) print(index) for x,y in index: if x==y: a[x,y] =0 print(a)