我正在尝试获取A中每一行i对应于列b [i]的值
我可以不使用for循环吗?
A = np.array([[35, 2, 23, 22], [44, 21, 15, 4], [44, 21, 15, 4], [37, 4, 17, 41], [33, 4, 4, 18], [35, 2, 23, 22]])
b = np.array([0,1,1,2,3,0])
C = zeros(len(b),1)
for i in range(6):
C[i] = A[i][b[i]]
答案 0 :(得分:1)
由于要顺序索引A
的行,因此除了np.arange(len(A))
之外,还可以使用 b
进行索引以获得所需的输出:>
A[np.arange(len(A)), b]
# array([35, 21, 21, 17, 18, 35])
显示其工作原理:
# A np.arange(len(A)) b array([[35, 2, 23, 22], [0, 0] [44, 21, 15, 4], [1, 1] [44, 21, 15, 4], [2, 1] [37, 4, 17, 41], [3, 2] [33, 4, 4, 18], [4, 3] [35, 2, 23, 22]]) [5, 0]
答案 1 :(得分:1)
怎么样?
A[:,b].diagonal()
Out[133]: array([35, 21, 21, 17, 18, 35])