2017-02-05 103 views
1

我一直在試圖獲取包含元素nd的矩陣(A)的所有行索引。獲取滿足條件的Python矩陣的行索引

A的大小是4M * 4,這個操作需要大約12秒。

鏈接到文件:data

# Download the file named elementconnectivity before running this small script 


A=np.loadtxt('elementconnectivity') 
A=A.astype(int) 
nd=1103 
v=[i for i in range(len(A)) if nd in A[i]] 

有沒有做到這一點更快的方法?

+0

如果可以,請分享'A'和'nd'的樣本值。這會給我們更多的想法,知道你在做什麼樣的操作以及哪種解決方案更適合。 –

+0

你好Vivek - 我給出了樣本值 – Mechanician

回答

1

,這加快了很多帶些numpy的功能。您當前我的系統方法:

%timeit v=[i for i in range(len(A)) if nd in A[i]] 
1 loop, best of 3: 4.23 s per loop 

相反,這是約40倍的速度更快:

%timeit v = np.where(np.sum((A == nd), axis=1) > 0) 
10 loops, best of 3: 92.2 ms per loop 

您也可以看看np.in1d它類似於我在上面使用了A == nd,但可以用比較列表(類似於A == nd1或nd2或nd3)。

+0

謝謝,它的工作 – Mechanician

+0

我發現這甚至需要更少的時間 v = np.where(A == nd)[0] – Mechanician

+0

這不會給你你在找什麼!這是給你所有元素在哪裏A == nd。但是你想知道哪些行有任何元素== nd。這就是爲什麼你必須將它總結在一個軸上。 – VBB

0

我認爲更好的方式來完成,這是由於您使用numpy仍要使用迭代器而不是列表

idxs = (i for i in xrange(len(A)) if nd in A[i]) 
idxs.next() 
+0

得到了一個錯誤:<發生器對象在0x000007FFFEFFC3A8> – Mechanician

+0

這不是一個錯誤,是對生成器的引用。 [生成器](https://wiki.python.org/moin/Generators)不會馬上給出結果,相反,每次你需要一個值時,你都可以使用方法** next **來獲得它。 –

+0

能否請你解釋我該如何取回數組中的值,我很抱歉我不知道這 – Mechanician