[英]Finding index of the element in a numpy array witout using for loop
作為輸入,我有2d numpy數組,讓我們假設這個:
my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])
我必須找到該行和列中的元素之和== 0的那個數組中每個元素的索引。在這種情況下,答案將是(2,3),因為第二行中的元素之和= 0,第3列中的元素總和=0。到目前為止,我想到了這個:
solution = [(i, j) for i in range(my_array.shape[0]) for j in range(my_array.shape[1]) if 1 not in my_array[i] and 1 not in my_array[:, j]]
問題是,我想這樣做而不使用for循環。
我試過使用np.where
和np.sum
,結果是這樣:
np.where(np.sum(my_array, axis=1) == 0 and np.sum(my_array, axis=0) == 0)
但我最終遇到此錯誤:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
關於如何解決此錯誤或僅使用其他方法查找索引的任何建議?
嘗試合並兩個條件時where
表達式中出現where
的問題:
In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-210-46c837435a31> in <module>
----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
Out[211]: array([False, False, False, False])
您必須將==
測試包裝在()內,以便它首先出現,並且您必須使用&
進行元素級and
。 and
是標量運算,在布爾數組中不能很好地發揮作用。
行和列測試是:
In [212]: arr.sum(0)==0
Out[212]: array([False, False, False, True])
In [213]: arr.sum(1)==0
Out[213]: array([False, False, True, False])
但是您需要一種外部或笛卡爾組合,而不是簡單的按元素組合(如果行和列的數量不同,這將更加明顯)。
In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0)
Out[218]:
array([[False, False, False, False],
[False, False, False, False],
[False, False, False, True],
[False, False, False, False]])
In [219]: np.where(_)
Out[219]: (array([2]), array([3]))
或使用sum
的keepdims
參數:
In [220]: arr.sum(0, keepdims=True)==0
Out[220]: array([[False, False, False, True]])
In [221]: arr.sum(1, keepdims=True)==0
Out[221]:
array([[False],
[False],
[ True],
[False]])
In [222]: np.where(_220 & _221) # Out[220] etc
Out[222]: (array([2]), array([3]))
這是使用itertools產品的解決方案。 創建總和== 0的行和列的列表,並找到它們之間的組合。
from itertools import product
my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])
a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]
np.array(list(product(a,b)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.