1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個贊
In [3]: arr1 = np.array([
...: [1, 2, 3, 4],
...: [2, 3, 1, 4],
...: [2, 4, 1, 5],
...: ])
...:
...: arr2 = np.array([
...: [2, 4, 1, 5],
...: [2, 1, 3, 5],
...: [1, 2, 3, 4],
...: ])
廣播平等后跟all和的適當(dāng)組合any:
In [8]: (arr1[:,None,:]==arr2[None,:,:]).shape
Out[8]: (3, 3, 4)
In [9]: (arr1[:,None,:]==arr2[None,:,:]).all(axis=2)
Out[9]:
array([[False, False, True],
[False, False, False],
[ True, False, False]])
In [10]: (arr1[:,None,:]==arr2[None,:,:]).all(axis=2).any(axis=0)
Out[10]: array([ True, False, True])
In [12]: arr1[_]
Out[12]:
array([[1, 2, 3, 4],
[2, 4, 1, 5]])
帶套
In [19]: set([tuple(row) for row in arr1])
Out[19]: {(1, 2, 3, 4), (2, 3, 1, 4), (2, 4, 1, 5)}
In [20]: set([tuple(row) for row in arr2])
Out[20]: {(1, 2, 3, 4), (2, 1, 3, 5), (2, 4, 1, 5)}
In [21]: _19.intersection(_20)
Out[21]: {(1, 2, 3, 4), (2, 4, 1, 5)}
===
如果我擴(kuò)展arr2到 4 行:
...: arr2 = np.array([
...: [2, 4, 1, 5],
...: [2, 1, 3, 5],
...: [1, 2, 3, 4],
...: [1, 1, 1, 1],
...: ])
In [34]: (arr1[:,None,:]==arr2[None,:,:]).all(axis=2).any(axis=0)
Out[34]: array([ True, False, True, False])
anyon 0 產(chǎn)生一個 4 元素數(shù)組,它必須用于索引arr2(不像arr1我原來那樣):
In [35]: arr2[_]
Out[35]:
array([[2, 4, 1, 5],
[1, 2, 3, 4]])
或者any沿著另一個軸:
In [36]: (arr1[:,None,:]==arr2[None,:,:]).all(axis=2).any(axis=1)
Out[36]: array([ True, False, True])
In [37]: arr1[_]
Out[37]:
array([[1, 2, 3, 4],
[2, 4, 1, 5]])
產(chǎn)生all(在本例中)一個 (3,4) 數(shù)組:
In [38]: (arr1[:,None,:]==arr2[None,:,:]).all(axis=2)
Out[38]:
array([[False, False, True, False],
[False, False, False, False],
[ True, False, False, False]])
any可以減少行或列。
添加回答
舉報