【发布时间】:2014-06-19 10:42:49
【问题描述】:
我的问题与这篇文章类似(扩展版):Numpy extract row, column and value from a matrix。在那篇文章中,我从输入矩阵中提取大于零的元素,现在我也想提取对角线上的元素。所以在这种情况下,
from numpy import *
import numpy as np
m=np.array([[0,2,4],[4,0,0],[5,4,0]])
dist=[]
index_row=[]
index_col=[]
indices=np.where(matrix>0)
index_col, index_row = indices
dist=matrix[indices]
return index_row, index_col, dist
我们可以得到,
index_row = [1 2 0 0 1]
index_col = [0 0 1 2 2]
dist = [2 4 4 5 4]
现在这就是我想要的,
index_row = [0 1 2 0 1 0 1 2]
index_col = [0 0 0 1 1 2 2 2]
dist = [0 2 4 4 0 5 4 0]
我尝试将原始代码中的第 8 行编辑为此,
indices=np.where(matrix>0 & matrix.diagonal)
但出现此错误,
如何得到我想要的结果?请给我一些建议,谢谢!
【问题讨论】:
-
您需要括号:
(matrix>0) & matrix.diagonal,因为运算符优先级。 -
@HYRY 我尝试了另一个错误:TypeError: unsupported operand type(s) for &: 'tuple' and 'builtin_function_or_method'
标签: python arrays numpy indexing diagonal