迭代numpy数组以比较不同数组的列

时间:2017-08-10 15:32:58

标签: python arrays numpy

我是编程新手并且有一个问题。如果我有两个numpy数组:

A = np.array([[1,0,3], [2,6,5], [3,4,1],[4,3,2],[5,7,9]], dtype=np.int64)  
B = np.array([[3,4,5],[6,7,9],[1,0,3],[4,5,6]], dtype=np.int64)

我想将数组A的最后两列与数组B的最后两列进行比较,然后如果它们相等,则将整行输出到新数组。因此,这两个数组的输出将是:

[1,0,3
1,0,3
5,7,9
6,7,9]

因为即使第一个元素与最后两行不匹配,最后两个元素也是如此。

到目前为止,这是我的代码,但它甚至还没有接近工作。谁能给我一些提示?

column_two_A = A[:,1]
column_two_B = B[:,1]

column_three_A = A[:,2]
column_three_B = B[:,2]

column_four_A = A[:,3]
column_four_B = B[:,3]

times = A[:,0]

for elementA in column_three_A: 
    for elementB in column_three_B: 
        if elementA == elementB: 
            continue 
        for elementC in column_two_A: 
            for elementD in column_two_B: 
                if elementC == elementD: 
                    continue
                for elementE in column_four_A: 
                    for elementF in column_four_B: 
                        if elementE == elementF:
                            continue 
                        element.append(time)
 print(element)

2 个答案:

答案 0 :(得分:1)

Numpy为这类任务拥有许多功能。以下是检查A的值是否在B中的解决方案。添加print()语句并检查chkchk2x是什么。

import numpy as np
A = np.array([[1,0,3], [2,6,5], [3,4,1],[4,3,2],[5,7,9]], dtype=np.int64)
B = np.array([[3,4,5],[6,7,9],[1,0,3],[4,5,6]], dtype=np.int64)

c = []

for k in A:

    chk = np.equal(k[-2:], B[:, -2:])
    chk2 = np.all(chk, axis=1)
    x = (B[chk2, :])
    if x.size:
        c.append(x)

print(c)

答案 1 :(得分:0)

我想我一整夜都熬夜了......谢谢你!

 `for i in range(len(A)):
     for j in range(len(B)):
         if A[i][1] == B[j][1]:
           if A[i][2] == B[j][2]:
               print(B[j])
               print(A[i])`