假設我們有兩個陣列,就像這兩個陣列一樣:
A=np. array([[1, 4, 3, 0, 5], [6, 0, 7, 12, 11], [20, 15, 34, 45, 56]] )
B=np.array([[4, 5, 6, 7]] )
我打算寫一段代碼,在這段代碼中,我可以根據陣列B中的值找到陣列A的索引,例如 陣列B中的值 例如,我希望最終的結果是這樣的:
C=[[0 1]
[0 4]
[1 0]
[1 2]]
誰能為我提供一個解決方案或提示?
uj5u.com熱心網友回復:
你的意思是?
在[375]: np.isin(A,B[0] )
Out[375]。
array([[False, True, False, True],
[True, False, True, False, False]。
[False, False, False, False]] )
在[376]: np.argwhere(np.isin(A,B[0] ))
Out[376]。
array([[0, 1],
[0, 4] 。
[1, 0]。
[1, 2]])
B形狀的(1,4),其中初始的1不是必須的。 這就是為什么我使用了B[0],盡管isin,通過in1d無論如何也要把它拉開。
where是結果往往更有用
在[381]: np.where(np.isin(A,B))
輸出[381]。(array([0, 0, 1, 1]) 。array([1, 4, 0, 2] )
盡管這有點難以理解。
另一種獲取isin陣列的方法:
在[383]。(A==B[0,:,None,None])。 any(axis=0)
Out[383]。
array([[False, True, False, True],
[True, False, True, False, False]。
[False, False, False, False]] )
uj5u.com熱心網友回復:
你可以通過使用np.where()來嘗試這種方式。
index = [] 。
for num in B。
for nums in num:
x,y = np.where(A == nums)
index.append([x,y])
print(index)
>>陣列([0,1]。
[0,4]。
[1,0]。
[1,2]])
uj5u.com熱心網友回復:
用zip和np.where:
>>> list(zip(*np. where(np.in1d(A, B).reshape(A.shape)))))
[(0, 1), (0, 4), (1, 0), (1, 2)]。
另一種方法是:
>>> np.vstack(np.where(np.isin(A,B)) .transpose()
array([[0, 1] 。
[0, 4]。
[1, 0]。
[1, 2] ], dtype=int64)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/326865.html
標籤:
