简体   繁体   English

从矩阵对角线上提取大量数值

[英]Numpy extract values on the diagonal from a matrix

My question is similar(the expanded version) to this post: Numpy extract row, column and value from a matrix . 我的问题与此帖子类似(扩展版本): Numpy从matrix提取行,列和值 In that post, I extract elements which are bigger than zero from the input matrix, now I want to extract elements on the diagonal , too. 在那篇文章中,我从输入矩阵中提取大于零的元素,现在我也想在对角线上提取元素 So in this case, 所以在这种情况下

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

we could get, 我们可以得到,

index_row = [1 2 0 0 1]
index_col = [0 0 1 2 2]
dist = [2 4 4 5 4]

and now this is what I want, 现在这就是我想要的

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]

I tried to edit line 8 in the original code to this, 我试图在原始代码中编辑第8行,

indices=np.where(matrix>0 & matrix.diagonal)

but got this error, 但是出现了这个错误,

在此处输入图片说明

How to get the result I want? 如何获得我想要的结果? Please give me some suggestions, thanks! 请给我一些建议,谢谢!

You can use following method: 您可以使用以下方法:

  1. get the mask array 获取遮罩数组
  2. fill diagonal of the mask to True 将蒙版的对角线填充为True
  3. select elements where elements in mask is True 选择蒙版中的元素为True的元素

Here is the code: 这是代码:

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

m[mask]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM