簡體   English   中英

獲取 numpy 數組的正確索引

[英]getting correct index of numpy array

我必須成對比較 np.arrays 並且我需要返回索引。

我的代碼是:

import numpy as np
Vals = np.array([[1.0, 1.0], [2., 2.], [1., 2.], [2., 1.], [3., 3.], [3., 3.]])
for Val in itertools.combinations(Vals,2):
    X1 = Val[0][0]
    X2 = Val[1][0]
    Y1 = Val[0][1]
    Y2 = Val[1][1]
    Index1 = np.where( (Vals == Val[0]).all(axis=1))[0][0]
    Index2 = np.where( (Vals == Val[1]).all(axis=1))[0][0]
    
    print(X1,Y1,Index1)
    print(X2,Y2,Index2)

這運行良好,直到兩個或多個具有相同值的元組在 Vals 中(如示例中所示)。 np.where 會返回這個元組在數組中的第一次出現,所以我得到了錯誤的索引。 如何獲得正確的索引?

for i, j in itertools.combinations(range(len(Vals)), 2):
    print(Vals[i], i, "|", Vals[j], j)
[1. 1.] 0 | [2. 2.] 1
[1. 1.] 0 | [1. 2.] 2
[1. 1.] 0 | [2. 1.] 3
[1. 1.] 0 | [3. 3.] 4
[1. 1.] 0 | [3. 3.] 5
[2. 2.] 1 | [1. 2.] 2
[2. 2.] 1 | [2. 1.] 3
[2. 2.] 1 | [3. 3.] 4
[2. 2.] 1 | [3. 3.] 5
[1. 2.] 2 | [2. 1.] 3
[1. 2.] 2 | [3. 3.] 4
[1. 2.] 2 | [3. 3.] 5
[2. 1.] 3 | [3. 3.] 4
[2. 1.] 3 | [3. 3.] 5
[3. 3.] 4 | [3. 3.] 5

您是否嘗試過使用 zip 串聯遍歷每個數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM