我有一个矩阵,我想编写一个脚本来提取大于零的值,其行号和列号(因为该值属于该(行,列)),这是一个示例,
from numpy import *
import numpy as np
m=np.array([[0,2,4],[4,0,4],[5,4,0]])
index_row=[]
index_col=[]
dist=[]
我想将行号存储在索引行, 中的列号索引列,以及值dist。所以在这种情况下,
index_row = [0 0 1 1 2 2]
index_col = [1 2 0 2 0 1]
dist = [2 4 4 4 5 4]
如何添加代码来实现这个目标?感谢您给我建议。
您可以使用numpy.where http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html为了这:
>>> indices = np.where(m > 0)
>>> index_row, index_col = indices
>>> dist = m[indices]
>>> index_row
array([0, 0, 1, 1, 2, 2])
>>> index_col
array([1, 2, 0, 2, 0, 1])
>>> dist
array([2, 4, 4, 4, 5, 4])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)