【问题标题】:Numpy extract values on the diagonal from a matrixNumpy 从矩阵的对角线上提取值
【发布时间】: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


【解决方案1】:

您可以使用以下方法:

  1. 获取掩码数组
  2. 将蒙版的对角线填充为 True
  3. 选择掩码中的元素为 True 的元素

代码如下:

m=np.array([[0,2,4],[4,0,0],[5,4,0]])
mask = m > 0
np.fill_diagonal(mask, True)

m[mask]

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2012-04-15
    • 2018-10-03
    • 2020-02-05
    • 1970-01-01
    • 2021-12-12
    • 2012-02-12
    • 2017-01-07
    • 2015-11-13
    相关资源
    最近更新 更多