我有一個矩陣“x”和一個陣列“索引”。我只想在矩陣“x”中找到“索引”陣列的位置(行號)。例子:
x = np.array([[0, 0],
[1, 0],
[2, 0],
[0, 1],
[1, 1],
[2, 1],
[0, 2],
[1, 2],
[2, 2],
[0, 3],
[1, 3],
[2, 3],])
index = [2,1]
在這里,如果我使用代碼:
np.where((x[:,0]==index[0]) & (x[:,1]==index[1]))[0]
它正在作業。
但是,如果我有 N 列(而不是 2)的矩陣“x”,我必須在 np.where 引數中使用回圈。我試過這個:
np.where((for b in range(2):(x[:,b]==index[b]) & (x[:,b]==index[b])))[0]
然后它顯示“無效語法”錯誤。你能幫我解決這個問題嗎?提前致謝。
uj5u.com熱心網友回復:
以下代碼將同時處理index
串列或 numpy 陣列以及是否在 中包含多個索引陣列index
,而不僅僅是一個:
x = np.array([[0, 0, 7],
[1, 0, 8],
[2, 3, 11],
[0, 1, 1],
[1, 1, 9],
[2, 1, 4], # <--
[0, 2, 7],
[1, 2, 3],
[2, 1, 4], # <--
[2, 2, 1],
[0, 3, 2],
[1, 3, 11], # <--
[1, 3, 8],
[2, 3, 8],])
index = np.array([[2, 1, 4], [1, 3, 11]]) # --> can be list index = [2, 1, 4]
可以通過以下方式完成:
np.where((x == np.atleast_2d(index)[:, None]).all(-1))[1]
# [ 5 8 11]
uj5u.com熱心網友回復:
僅與它的where
引數一樣好,在傳遞給where
函式之前會對其進行完整評估:
In [292]: np.where((x[:,0]==index[0]) & (x[:,1]==index[1]))[0]
Out[292]: array([5], dtype=int64)
條件是一個布爾陣列:
In [293]: (x[:,0]==index[0]) & (x[:,1]==index[1])
Out[293]:
array([False, False, False, False, False, True, False, False, False,
False, False, False])
看起來你試圖創建一個for loop
:
for b in range(2):
(x[:,b]==index[b]) & (x[:,b]==index[b])
使用它作為引數不是有效的python。你可以創建一個函式
def foo(x,index):
res = []
for b in ....
res.append(...)
return res
但更簡單的語法是串列推導:
In [294]: [x[:,i]==index[i] for i in range(2)]
Out[294]:
[array([False, False, True, False, False, True, False, False, True,
False, False, True]),
array([False, False, False, True, True, True, False, False, False,
False, False, False])]
并且陣列可以與 a 組合np.all
:
In [295]: np.all([x[:,i]==index[i] for i in range(2)], axis=0)
Out[295]:
array([False, False, False, False, False, True, False, False, False,
False, False, False])
但正如其他人所展示的那樣,您不需要迭代。讓 (n,2)x
對 (2,) 廣播index
:
In [296]: x==index
Out[296]:
array([[False, False],
[False, False],
[ True, False],
[False, True],
[False, True],
[ True, True],
[False, False],
[False, False],
[ True, False],
[False, False],
[False, False],
[ True, False]])
In [297]: (x==index).all(axis=1)
Out[297]:
array([False, False, False, False, False, True, False, False, False,
False, False, False])
uj5u.com熱心網友回復:
您可以使用broadcasting
:
np.where((x == np.array(index).reshape(1, -1)).all(1))
甚至:
np.where((x == np.array(index)[None, :]).all(1))
兩者都導致:
(array([5], dtype=int64),)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494387.html
上一篇:創建帶狀(或帶狀)矩陣的有效方法