[英]Comparing Two 2-D tuples with numpy in Python
我有兩個嵌套的元組,分別名為coord和coord2 , 我想看看第一個元組中的一組坐標是否與另一個元組中的一組坐標相匹配,而不管索引如何。
例如,
coord[0][1] = 127,
coord[0][2] = 128,
coord[0] = 127,128,129....
coord[1][0] = 302,
coord[1] = 302,303,304 ....
現在,我可以看到每個索引是否與另一個元組的索引完全匹配,但是看不到另一個中是否存在一個集合。 這是我的代碼:
for i in range(60):
if (coord[0][i]) == (coord2[0][i]) and (coord[1][i]) == (coord2[1][i]):
print(coord[0][i])
print(coord[1][i])
count += 1
total += 1
else:
total += 1
我應該怎么做呢? 我在python中使用numpy數組很新
我已經寫了一些新代碼,
for i in range(60):
if coord2[0][i] and coord2[1][i] in coord:
count += 1
total += 1
else:
total += 1
在我看來,這應該告訴我第二個元組中是否有任何一組坐標。 但是我遇到一個錯誤,說ValueError:具有多個元素的數組的真值不明確。 使用a.any()或a.all()
其實想通了。
for i in range(200):
if (coord2[0][i]) in coord[0] and coord2[1][i] in coord[1]:
count += 1
total += 1
else:
total += 1
如果您只是想知道一個矩陣中的任何坐標是否存在於另一個矩陣中,則這是一種實現方法。
import itertools
import numpy
首先讓我們獲取矩陣的所有可能的索引組合
idx = tuple(e for e in itertools.product(range(len(coord)), repeat=2))
((0, 0),
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 1),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(3, 3))
然后讓我們比較兩個索引矩陣,看看是否有其他點存在
coord = np.arange(16).reshape(4,4)
coord1 = np.random.randint(1, size=(4,4))
np.equal([coord[_idx] for _idx in idx],[coord1[_idx] for _idx in idx])
array([ True, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False], dtype=bool)
編輯:如果您只是想要出現的次數,那么它將變為
np.sum(np.equal([coord[_idx] for _idx in idx],[coord1[_idx] for _idx in idx]))
>>1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.