2014-06-17 2 views
1

행렬이 있고, 0보다 큰 값, 행 번호 및 열 번호를 추출하는 스크립트를 작성하고 싶습니다 (값이 (행, 여기 열)), 그리고매트릭스에서 Numpy 행, 열 및 값

from numpy import * 
import numpy as np 

m=np.array([[0,2,4],[4,0,4],[5,4,0]]) 
index_row=[] 
index_col=[] 
dist=[] 

나는 index_row에 행 번호를 저장하려면, 예입니다, index_col의 열 번호, DIST의 값. 따라서이 경우

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

이 목표를 달성하는 코드를 추가하는 방법은 무엇입니까? 제안 해 주셔서 감사합니다.

답변

4

당신은이에 대한 numpy.where를 사용할 수 있습니다

>>> 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]) 
+0

'mask = m> 1'을 계속 사용하면 약간 더 빠를 것이고, 그 값을'dist = m [mask]'로 검색하는데 사용됩니다. – Jaime

0

를이 이미 대답 하였지만, 나는 종종 모든 것을 좋아하지만 다소 cumbersome--로 np.where을 찾아, 상황에 따라 달라집니다. 이를 위해, 나는 아마 ziplist comprehension을 사용하십시오 :

index_row = [0, 0, 1, 1, 2, 2] 
index_col = [1, 2, 0, 2, 0, 1] 
zipped = zip(index_row, index_col) 
dist = [m[z] for z in zipped] 

zip 당신에게 인덱스 NumPy와 배열에 사용할 수있는 튜플의 iteratable을 줄 것이다.